Winsock - 等待调用accept()直到客户端真正尝试连接

时间:2013-06-08 12:24:40

标签: c++ winsock2

我正在使用Winsock API在C ++中创建服务器。我想知道是否有任何可能性只在某些连接实际到来时调用accept()函数,所以我不必在accept()上阻塞我的线程。换句话说,我想让我的线程等待并仅在客户端尝试连接时调用accept()函数。这可能吗?

1 个答案:

答案 0 :(得分:0)

当您使用Winsock时,您可以使用Microsoft特定的扩展功能AcceptEx。这允许你执行接受作为"重叠的I / O",这在概念上意味着接受在后台运行,你可以偶尔进入并检查它是否发生,或者通过检查OverlappedResult,或在OverlappedHandle上执行等待。 AcceptEx也可以选择执行第一次接收。

如果不编写所有代码并对其进行全面测试,那么以下内容应该有效:

// The following:
//   Has no error checking
//   Assumes sListen is a bound listening socket
//   Some other assumptions I've not listed :)

// Allocate space to store the two sockaddr's that AcceptEx will give you
// 
char lpOutputBuffer[sizeof((sockaddr_in)+16) * 2];

SOCKET sAccept = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
WSAOVERLAPPED olOverlap;

ZeroMemory(&olOverlap, sizeof(WSAOVERLAPPED));
olOverlap.hEvent = WSACreateEvent();

DWORD dwBytes;

BOOL bAcceptRet =
    AcceptEx(sListen, // the listen socket
             sAccept, // the socket to use for the accepted connection
             lpOutputBuffer, // where to store the received information
             0, // don't do a receive, just store the local and remote addresses
             sizeof((sockaddr_in)+16), // size of the local address area
             sizeof((sockaddr_in)+16), // size of the remote address area
             &dwBytes, // set to received bytes if we complete synchronously
             &olOverlap); // our overlapped structure

if (bAcceptRet) {
    // the function completed synchronously.
    // lpOutputBuffer should contain the address information.
    // sAccept should be a connected socket
} else {
    // the function didn't complete synchronously, so is the accept Pending?
    if (ERROR_IO_PENDING == WSAGetLastError()) {
        // in this case, our Accept hasn't happened yet...
        // later in our code we can do the following to check if an accept has occurred:
        // note that the FALSE tells WSAGetOverlappedResult not to wait for the I/O to complete
        // it should return immediately
        ...
        DWORD dwFlags;
        if (WSAGetOverlappedResult(sListen, &olOverlap, &dwBytes, FALSE, &dwFlags)) {
            // the accept has succeeded, so do whatever we need to do with sAccept.
        }
        ...
    }
}

当然,这是一个非常快速,黑客攻击的可能非工作,不可编译的代码,但它应该让你知道如何做一些类似于你想要的东西,以及在哪里看。

顺便提一下,设置hEvent结构的WSAOVERLAPPED参数在技术上并不是必需的,但这样做可以让实际等待请求完成:

if (WAIT_OBJECT_0 == WaitForSingleObject(olOverlap.hEvent, INFINITE)) {
    // The accept occurred, so do something with it
}

我现在要等一个人指出我代码中的巨大错误......