套接字:发送邮件给几个客户端
我想写一个服务器,接受来自多个客户端的邮件,直到它收到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);
}
FYI的bzero()功能已被弃用(标记为在POSIX.1-2001 LEGACY):(3)在新的程序使用memset的。 POSIX.1-2008删除了bzero的规格()
回答:
你试过zeroMq了吗?例如 http://zguide.zeromq.org/cpp:rrworker
以上是 套接字:发送邮件给几个客户端 的全部内容, 来源链接: utcz.com/qa/259731.html