我想寫一個服務器,接受來自多個客戶端的郵件,直到它收到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);
}
您是否嘗試過設置Cookie? – Arash
@ArashMohammadi不,我還沒有嘗試過,現在我要讀一下它。如果服務器和所有客戶端都在同一臺PC上,Cookie會起作用嗎? – vgeclair
如果客戶端可以發送多條消息,則可能需要查看「select」或「epoll」。 – user4581301