How to set up a connection timeout in Socket

zhaozj2021-02-08  259

How to set up a connection timeout in Socket ANTGHAZI / 2001.12.14 Home: ANTGHAZI.YEAH.NET

Turning 9CBS with Chinese Yahoo, did not find how to set up the connection timeout of Socket, and ask the brothers of this question already have a lot, here even how to set up a Socket's Connect timeout. Setting up the timeout of Connect is very simple, some people mentioned on 9CBS mentioned using Select, but there is no satisfactory and complete answer. Even the SELECT function is also a SELECT function. This function is integrated in Winsock1.1, simply, "the role makes it want to avoid the application that is locked in the socket call, take an orderly manner, At the same time, multiple sockets are managed ("Windows Network Programming Technology". See "Windows Network Programming Technology" for use and explanation. Before using this function, you need to set the socket to a non-lock mode, so that you will jump immediately, and it will also generate a WSAEWOULDBLOCK error. This error does not matter. It is true timeout to perform SELECT.

WSADATA wsd; SOCKET cClient; int ret; struct sockaddr_in server; hostent * host = NULL; if (WSAStartup (MAKEWORD (2,0), & wsd)) {return 0;} cClient = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (cclient == invalid_socket) {return 0;} // set recv and send time outint timeout = 6000; // Setting send timeout 6 seconds if (: setsockopt, sol_socket, so_sndtimeo, (char *) & timeout, sizeof Timeout) == SOCKET_ERROR) {Return 0;} Timeout = 6000; // Settings receiving timeout 6 seconds if (: setsockopt, cclient, sol_socket, so_rcvtimeo, (char *) & timeout, sizeof (timeout)) == Socket_ERROR) {RETURN 0;} // Set non-blocking method connection unsigned long ul = 1; RET = IOCTLSOCKET (CClient, Fionbio, (unsigned long *) & ul); if (RET == Socket_ERROR) RETURN 0; // Connect Server.sin_Family = AF_INET; server.sin_port = htons (25); server.sin_addr .s_addr = inet_addr ((LPCSTR) pSmtp); if (server.sin_addr.s_addr == INADDR_NONE) {return 0;} connect (cClient, (const struct sockaddr *) & server, sizeof (server)); // SELECT model, set timeout struct timeval timeout; fd_set r; fd_set r; fd_set (cclient, & r); timeout.tv_sec = 15; // Connect timeout 15 second Timeout .tv_usec = 0; RET = SELECT (0, 0, &) R, 0, & Timeout; if (RET <= 0) {:: clossocket (cclient); return 0; // General non-lock mode jacket is more difficult to control, can consider resetting back blocking mode Unsigned Long according to actual conditions UL1 = 0; RET = IOCTLSocket (cclient, fionbio, (unsigned long *) & ul1); if (RET == Socket_ERROR) {:: clossoSocket (cclient); return 0;} If there is an unknown or wrong place, welcome to correct. Mailto: Antghazi@163.nethttp: //antghazi.yeah.netantghazi/2001.12.14

转载请注明原文地址:https://www.9cbs.com/read-3038.html

New Post(0)