取消阻塞套接字的连接?

时间:2014-04-27 03:13:35

标签: c++ sockets winsock2

我使用以下代码进行客户端套接字

int ConnectToServerSocket
    (
        char*   _serverIP,          //in
        char*   _serverPort,        //in
        SOCKET& _connectedSocket    //out
    )
{
    struct addrinfo *addrResult = NULL,hints;
    ZeroMemory(&hints, sizeof (hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_family = AF_UNSPEC;
    int result = 0;
    if (getaddrinfo(_serverIP, _serverPort, &hints, &addrResult))
    {
        int err = WSAGetLastError();
        return err;
    }

    _connectedSocket = socket(addrResult->ai_family, addrResult->ai_socktype, addrResult->ai_protocol);
    if (_connectedSocket == INVALID_SOCKET)
    {
        int err = WSAGetLastError();
        freeaddrinfo(addrResult);
        return err;
    }

    if (connect(_connectedSocket, addrResult->ai_addr, (int)addrResult->ai_addrlen) != 0)
    {
        int err = WSAGetLastError();
        closesocket(_connectedSocket);
        _connectedSocket = INVALID_SOCKET;
        return err;
    }
    return 0; //successful
}

问题是我想随时取消连接,在取消事件按钮中,我调用了closesocket(_connectedSocket);但是在返回错误后很久就被connect()函数阻止了。

有人可以告诉我如何立即中断connect()功能吗?

非常感谢,

T& T公司

1 个答案:

答案 0 :(得分:1)

让另一个线程执行connect。这将允许您使用任何方法等待其他线程,无论多长时间,以及您希望的任何中止机制。

您不需要中止connect本身。