【发布时间】:2018-05-16 21:11:40
【问题描述】:
我正在尝试编写一个服务器,它接受来自多个客户端的消息,直到它接收到其中 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);
}
【问题讨论】:
-
你试过设置cookies吗?
-
@ArashMohammadi 不,我没有尝试过,我现在要阅读它。如果服务器和所有客户端都在同一台 PC 上,cookie 会起作用吗?
-
如果客户端可以发送多条消息,您可能需要查看
select或epoll。 -
目前每个客户端只有一条消息,客户端只能为下一批发送下一条消息。
-
另请注意:
read不保证您会收到完整的消息。您将收到 0 到read_len字节。n是实际读取的字节数,0 表示套接字断开连接。如果n小于消息所需的字节数,则必须循环直到获得整个消息。