Windows - Wait on event and socket simulatenously

烂漫一生 提交于 2021-02-18 07:47:59

问题


I'm writing Win32-API C code that needs to wait for new TCP connections and on the other side can be closed at any time by any other process/thread.

Therefore, I need to somehow WaitForSingleObject on the stop event and wait for connections using WSAAccept simultaneously.

I tried WaitForMultipleObjects on both socket and handle but new connection won't trigger the function (also WaitForSingleObject on the socket won't be triggered on a new connection).

Any idea?


回答1:


You need to use WSAWaitForMultipleEvents. For sockets, here's some pseudo code:

HANDLE hEvent[1];
hEvent[0] = WSACreateEvent();
WSAEventSelect(hSocket, hEvent[0], FD_READ | FD_WRITE);

while (WSAWaitForMultipleEvents(...)) {
    if (WSAEnumNetworkEvents(...)) { // Multiple events max exist
        if (... & FD_ACCEPT) {
        }
        if (... & FD_WRITE) {
        }
        ....
    }
}

If you use multiple events (e.g. a stop event to signal the thread to stop), use the return value from the WSAWaitForMultipleEvents to determine the signalled event (as you do with WaitForMultipleObjects).




回答2:


You cannot wait on socket handles directly.

WSAAccept() is synchronous, the only way to abort it is to close the listening socket.

For what you are attempting to do, use AcceptEx() instead, which is asynchronous and supports Overlapped I/O and I/O Completion Ports.

If you use Overlapped I/O, you can associate a standard Win32 event object to each Overlapped I/O capable socket operation (AcceptEx(), WSARecv(), WSASend(), etc), and use a standard Win32 event object for your stop event. And then you can use a WaitForMultipleObjects() loop to know which event(s) are signaled and act accordingly.

If you use an I/O Completion Port, you don't need event objects at all. You can associate each socket with a single IOCP queue, and your IOCP handler (either a call to GetQueuedCompletionStatus() or a callback function) will be notified whenever each IOCP capable socket operation completes. You can then use PostQueuedCompletionStatus() to post a custom stop message to the IOCP queue. You IOCP handler can act accordingly based on what kind of event it receives.



来源:https://stackoverflow.com/questions/41743043/windows-wait-on-event-and-socket-simulatenously

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