VC ++ uses setsockopt () to control the timeout between recv () and send (). setsockoptrecv
In the send () and recv () processes, sometimes due to network conditions and other reasons, sending and receiving cannot be performed as expected, and sending and receiving timeout control is set:
The following is an excerpt from the previous online article. It is written in this way:
Int nNetTimeout = 1000; // 1 second, // set the sending timeout setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & nNetTimeout, sizeof (int )); // set the receiving timeout value setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & nNetTimeout, sizeof (int ));
There are two notes:
1) The fourth parameter of recv () must be MSG_WAITALL (setting MSG_DONTWAIT does not block receiving data after a connection is established ), in blocking mode, data ranging from a specified number to a specified number will not be returned unless the timeout time is reached. It should also be noted that as long as the receiving timeout is set, it is also valid when no MSG_WAITALL is available. In the end, timeout means that you will not let your program wait for a long time, and you will only return it once at a certain time.
2) even if the wait time-out value is not reached, but the other party has closed the socket, The recv () will immediately return and receive the amount of data returned.
Int rst; int nNetTimeout = nTimeOut; // 1 second, SOCKET sockClient = socket (AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv. sin_addr.S_un.S_addr = htonl (wIpAddr); addrSrv. sin_family = AF_INET; addrSrv. sin_port = htons (nPort); setsockopt (sockClient, SOL_SOCKET, SO_SNDTIMEO, (char *) & nNetTimeout, sizeof (int); rst = connect (sockClient, (SOCKADDR *) & addrSrv, sizeof (SOCKADDR); if (rst! = 0) {return 0;} setsockopt (sockClient, SOL_SOCKET, SO_SNDTIMEO, (char *) & nNetTimeout, sizeof (int); send (sockClient, "1", 3, 0); // the last digit 0 is the default char recvbuf [4]; memset (recvbuf, 0, 4); setsockopt (sockClient, SOL_SOCKET, SO_RCVTIMEO, (char *) & nNetTimeout, sizeof (int); recv (sockClient, recvbuf, 100, 0); closesocket (sockClient ); if (recvbuf [0] = 'C' & recvbuf [1] = 'D') {return 1;} else {return 0 ;}