I'am trying to set my own timeot for connect() function.
my code works well with default connection like this:
bool connectFUNC4(char * ipaddr) {
WSADATA wsa;
struct sockaddr_in server;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
return false;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
return false;
server.sin_addr.s_addr = inet_addr(ipaddr);
server.sin_family = AF_INET;
server.sin_port = htons(5577);
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
return false;
return true;
}
I understand idea with blocking and not blocking connection, and I've found solution with setting to nonblocking mode and timeout. It always finished successful but communication does not work.
bool connectFUNC3(char * ipaddr) {
WSADATA wsa;
struct sockaddr_in server;
server.sin_addr.s_addr = inet_addr(ipaddr);
server.sin_family = AF_INET;
server.sin_port = htons(5577);
unsigned long block = 1;
ioctlsocket((unsigned int)sock, FIONBIO, &block);
WSAGetLastError();
int ret = connect(sock, (struct sockaddr *)&server, sizeof(server));
timeval time_out;
time_out.tv_sec = 5;
time_out.tv_usec = 0;
fd_set setW, setE;
FD_ZERO(&setW);
FD_SET(sock, &setW);
FD_ZERO(&setE);
FD_SET(sock, &setE);
select(0, NULL, &setW, &setE, &time_out);
bool flag;
if (FD_ISSET(sock, &setW))
{
// connection successful
flag = true;
}
else if (FD_ISSET(sock, &setE))
{
// connection fail
flag = false;
}
else
{
// connection timeout
flag = false;
}
block = 0;
ioctlsocket((unsigned int)sock, FIONBIO, &block);
return flag;
}
Please help to make it work, or to find another solution (multithread not usable in my case). Thank you.