1 //tcpclient.h2 #ifndef Tcpclient_h3 #defineTcpclient_h4#include <winsock2.h>5#include <ws2tcpip.h>6#include <iostream>7#include <cstdio>8 9 Ten externSOCKET Connectsocket; One intConnectser (); A - #endif //Tcpclient_h
1 //tcpclient.c2#include"tcpclient.h"3 4 using namespacestd;5 6 //need to link with ws2_32.lib7 //#pragma comment (lib, "Ws2_32.lib")8SOCKET Connectsocket;//define a connection socket to use when sending a receive9 /*******************************************************Ten * * Function name: Connectser One * * Function function: Connect server A * * Input: None - * * Output: None - * * Note: server ip:192.168.5.1 port:8010 timeout connection: 1s the ********************************************************/ - intConnectser () - { - //---------------------- + //Initialize Winsock - BOOLRET =false; + intError =-1; A intLen =sizeof(int); at wsadata wsadata; - intIresult = WSAStartup (Makeword (2,2), &wsadata); - if(Iresult! =no_error) { -RET =false; - returnret; - } in //---------------------- - //Create a SOCKET for connecting to server toConnectsocket =sockets (Af_inet, Sock_stream, ipproto_tcp); + if(Connectsocket = =invalid_socket) { - WSACleanup (); theRET =false; * returnret; $ }Panax Notoginseng //---------------------- - //the SOCKADDR_IN structure specifies the address family, the //IP address, and port of the server to is connected to. + sockaddr_in ClientService; Aclientservice.sin_family =af_inet; theCLIENTSERVICE.SIN_ADDR.S_ADDR = inet_addr ("192.168.5.1"); +Clientservice.sin_port = htons (8010); - $ //Connection Timeout 1 seconds $ structtimeval timeout; - Fd_set R; -UnsignedLongUL =1; theIoctlsocket (Connectsocket, Fionbio,&ul);//set to non-blocking mode - //If the connection fails, set the timeoutWuyi if(-1= = Connect (connectsocket, (SOCKADDR *) &clientservice,sizeof(ClientService))) { theFd_zero (&R); -Fd_set (Connectsocket, &R); WuTimeout.tv_sec =1;//Connection Timeout 1 seconds -Timeout.tv_usec =0; About if(Select(0, NULL, &R, NULL, &timeout) >0 ){ $GetSockOpt (Connectsocket, Sol_socket, So_error, (Char*) &error,/*(socklen_t *)*/&len); - if(Error = =0) -RET =true; - Else ARET =false; + } the Else -RET =false; $ } the //If the connection is successful, return to RET 1 the Else theRET =true; theUL =0; -Ioctlsocket (Connectsocket, Fionbio, &ul);//set to blocking mode block time is timeout time in returnret; the}
Windows Settings Connect Timeout