套接字:向多个客户端

时间:2017-12-03 06:14:34

标签: c++ sockets

我试图编写一个接受来自多个客户端的消息的服务器,直到收到其中的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);
}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情。

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):在新程序中使用memset(3)。 POSIX.1-2008删除了bzero()

的规范

答案 1 :(得分:-1)

你尝试过zeroMq吗? 例如http://zguide.zeromq.org/cpp:rrworker