套接字:向多个客户端发送消息
我正在尝试编写一个服务器,它接受来自多个客户端的消息,直到它接收到N个客户端的消息,处理这批数据,并向所有客户端发送回复"done“。
如果我在从客户端收到数据后立即向客户端发送消息"done“,则此代码可以正常工作。如何“保存”所有客户端,并在批处理完成后将消息发送给每个客户端?
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);
}
转载请注明出处:http://www.jixiangdc.com/article/20230526/1982503.html