Windows-模拟事件和套接字 [英] Windows - Wait on event and socket simulatenously

查看:89
本文介绍了Windows-模拟事件和套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写需要等待新的TCP连接的Win32-API C代码,另一方面,可以通过任何其他进程/线程在任何时间关闭它.

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.

因此,我需要以某种方式在Stop事件上使用WaitForSingleObject并同时等待使用WSAAccept的连接.

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

我在套接字和句柄上都尝试了WaitForMultipleObjects,但是新连接不会触发该函数(套接字上的WaitForSingleObject也不会在新连接上触发).

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).

有什么主意吗?

推荐答案

您需要使用

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) {
        }
        ....
    }
}

如果您使用多个事件(例如,停止事件来通知线程停止),请使用WSAWaitForMultipleEvents的返回值来确定发出信号的事件(与WaitForMultipleObjects相同).

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).

这篇关于Windows-模拟事件和套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆