polling recvfrom(), sendto()

时光怂恿深爱的人放手 提交于 2019-12-13 03:14:01

问题


I remake two detached threads to poll() cycle in server: for receiving and sending data. All work fine, until setting client's sending frequency to 16 ms (< ~200 ms). In this state one thread always wins the race and answers to only one client with ~1 us ping. What I need to do to send and receive data in poll() with two (or one) UDP sockets?

Part of server's code:

struct pollfd pollStruct[2];
// int timeout_sec = 1;

pollStruct[0].fd = getReceiver()->getSocketDesc();
pollStruct[0].events = POLLIN;
pollStruct[0].revents = 0;
pollStruct[1].fd = getDispatcher()->getSocketDesc();
pollStruct[1].events = POLLOUT;
pollStruct[1].revents = 0;

while(true) {
    if (poll(pollStruct, 2, 0 /* (-1 / timeout) */) > 0) {
        if (pollStruct[0].revents & POLLIN) {
            recvfrom(getReceiver()->getSocketDesc(), buffer, getBufferLength(), 0, (struct sockaddr *) &currentClient, getReceiver()->getLength());
            // add message to client's own thread-safe buffer
        }

        if (pollStruct[1].revents & POLLOUT) {
            // get message from thread-safe general buffer after processing
            // dequeue one
            if (!getBuffer().isEmpty()) {
                auto message = getBuffer().dequeue();
                if (message != nullptr) {
                    sendto(getDispatcher()->getSocketDesc(), "hi", 2, 0, message->_addr, *getDispatcher()->getLength());
                }
            }
        }

    }
}

来源:https://stackoverflow.com/questions/51986477/polling-recvfrom-sendto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!