gpt4 book ai didi

c++ - 套接字:向多个客户端发送消息

转载 作者:太空宇宙 更新时间:2023-11-04 12:53:53 24 4
gpt4 key购买 nike

我正在尝试编写一个服务器,它接受来自多个客户端的消息,直到它收到 N 个消息,处理这批数据并将回复“完成”发送给所有客户端。

如果我在收到来自客户端的数据后立即向客户端发送消息“完成”,则此代码可以正常工作。我怎样才能“保存”所有客户端并在批处理完成后向每个客户端发送消息?

while (true) {
listen(sock, 1000);
newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen);
n = read(newsock, buffer, read_len);
if (n < 0) {
cout << "ERROR reading from the socket" << endl;
continue;
}
memcpy(data + (msg_count * tuple_size), buffer, tuple_size);
n = write(newsock, "done\n", 5); //sending the message to the current client
msg_count++;
if (msg_count >= batch_size) {
msg_count = 0;
doSomethingWithTheData(data);
//I want to send the message to all the clients here
}
bzero(buffer, read_len);
}

最佳答案

尝试这样的事情。

while (true) {
std::list<int> socks;
listen(sock, 1000);
newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen);
n = read(newsock, buffer, read_len);
if (n < 0) {
cout << "ERROR reading from the socket" << endl;
continue;
}
memcpy(data + (msg_count * tuple_size), buffer, tuple_size);
socks.push_back(newsock);
msg_count++;
if (msg_count >= batch_size) {
msg_count = 0;
doSomethingWithTheData(data);

//I want to send the message to all the clients here
msg_count -= socks.size();
while (!socks.empty()) {
newsock = socks.front();
n = write(newsock, "done\n", 5); //sending the message to the current client
close(newsock);
socks.pop_front();
}
}
bzero(buffer, read_len);
}

仅供引用 bzero()函数已弃用(在 POSIX.1-2001 中标记为 LEGACY):在新程序中使用 memset(3)。 POSIX.1-2008 删除了 bzero() 的规范

关于c++ - 套接字:向多个客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com