سؤال

I'm using the following code for client socket

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
}

The problem is I want to cancel the connection anytime, In the cancel event button, I called closesocket(_connectedSocket); but it was blocked by connect() function so long after return the error.

Someone can show me how to interrupt the connect() function immediately?

Many thanks,

T&T

هل كانت مفيدة؟

المحلول

Have another thread do the connect. That will allow you to wait for that other thread using whatever method, for however long, and with whatever abort mechanism you wish.

You don't need to abort the connect itself.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top