• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

套接字:发送邮件给几个客户端

c/c++ 来源:vgeclair 3次浏览

我想写一个服务器,接受来自多个客户端的邮件,直到它收到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); 
} 


===========解决方案如下:

尝试类似这样的东西。

<code class="prettyprint-override">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); 
} 
</code>

FYI的bzero()功能已被弃用(标记为在POSIX.1-2001 LEGACY):(3)在新的程序使用memset的。 POSIX.1-2008删除了bzero的规格()


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)