i finished a program that just requests http pages from the internet and saves them to file (kind of like an offline viewer). anyway, ive noticed that sometimes, it would freeze for about 10 to 20 seconds, after further checking, i found out its caused by connect() and the webserver either cant/doesnt respond.
i looked up connect timeout on google, and found this method:
heres how i implemented it:Winsock API functions such as 'send()', 'recv()', 'connect()' etc. block because we are using blocking sockets. The next solution is to simply use non-blocking sockets instead. For a non-blocking socket, 'connect()' returns with 'WSAEWOULDBLOCK' error. However, the connection process goes on. Thus, one crude but simple way of adding a timeout is to issue a 'connect()' call and wait for a specified amount of time, then call a winsock function like 'getpeername()' or 'recv()' that needs a connected socket. If the error is 'WSAENOTCONN' we can safely assume that the socket is not connected and close the socket. The drawback of this method is that even if the connection occurs quickly, it will only be known after the specified timeout. We can reduce this effect by checking at intervals and abandoning the effort once the total time has elapsed.
when i do that, it doesnt time out after 5 seconds (like i set).. instead it times out after around 20 seconds with WSAETIMEDOUT.Code:SOCKET serverSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); if (connect(serverSocket, (sockaddr *)&addrServer, sizeof(addrServer)) != 0) { if (WSAGetLastError() != WSAEWOULDBLOCK) return INVALID_SOCKET; struct sockaddr addrTemp = {0}; int lenTemp = sizeof(addrTemp); unsigned int nStart = GetTickCount(), nTimeout = 5000; while (true) { if (getpeername(serverSocket, &addrTemp, &lenTemp) != 0) { if (WSAGetLastError() == WSAENOTCONN) { if (GetTickCount() > (nStart + nTimeout)) //connect timeout return INVALID_SOCKET; } } else { break; } Sleep(200); //check 5 times per second } }
i use getpeername() to check if the socket is connected.