// widonws: 默认设置socket TCP client connect为阻塞模式
void TcpConnect(char* strIP, UINT nPort)
{struct sockaddr_in serverAddress;SOCKET hSocket &#61; NULL;hSocket &#61; socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if( hSocket&#61;&#61;INVALID_SOCKET){return;}memset(&serverAddress, 0, sizeof(serverAddress)); serverAddress.sin_family &#61; AF_INET;serverAddress.sin_addr.s_addr &#61; inet_addr(strIP); serverAddress.sin_port &#61; htons((short)nPort); int iTimeOut &#61; 3000;setsockopt(hSocket,SOL_SOCKET,SO_RCVTIMEO,(char*)&iTimeOut,sizeof(iTimeOut));setsockopt(hSocket,SOL_SOCKET,SO_SNDTIMEO,(char*)&iTimeOut,sizeof(iTimeOut)); if( SOCKET_ERROR&#61;&#61;connect(hSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) ){ closesocket(hSocket);DWORD gle &#61; WSAGetLastError();return;}char buff[] &#61; "hello";int sl&#61;::send(hSocket,(char*)buff, sizeof(buff), 0);if( sl<0 ){closesocket(hSocket);return ;}closesocket(hSocket);
}// widonws: 设置socket TCP client connect非阻塞模式
void SockSelect(char* strIP, UINT nPort)
{SOCKET/*int*/ sockfd &#61; socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if(sockfd <0) {return;}struct sockaddr_in serv_addr;//以服务器地址填充结构serv_addrserv_addr.sin_family &#61; AF_INET;serv_addr.sin_addr.s_addr &#61; inet_addr(strIP);serv_addr.sin_port &#61; htons(nPort);int error &#61; -1;int len &#61; sizeof(int);timeval tm;fd_set set;unsigned long ul &#61; 1;ioctlsocket(sockfd, FIONBIO, &ul); //设置为非阻塞模式bool ret &#61; false;if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) &#61;&#61; -1){tm.tv_sec &#61; 3;tm.tv_usec &#61; 0;FD_ZERO(&set);FD_SET(sockfd, &set);if( select(sockfd&#43;1, NULL, &set, NULL, &tm) > 0){getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/&len);if(error &#61;&#61; 0) ret &#61; true;else ret &#61; false;} else ret &#61; false;}else ret &#61; true;ul &#61; 0;ioctlsocket(sockfd, FIONBIO, &ul); //设置为阻塞模式if(!ret) {closesocket( sockfd );fprintf(stderr , "Cannot Connect the server!/n");return;}fprintf( stderr , "Connected!/n");char buff[] &#61; "hello";int sl&#61;::send(sockfd,(char*)buff, sizeof(buff), 0);closesocket( sockfd );
}