1 //tcpclient.h 2 #ifndef TCPCLIENT_H 3 #define TCPCLIENT_H 4 #include <winsock2.h> 5 #include <ws2tcpip.h> 6 #include <iostream> 7 #include <cstdio> 8 9 10 extern SOCKET ConnectSocket; 11 int ConnectSer(); 12 13 #endif // TCPCLIENT_H
1 //tcpclient.c 2 #include "tcpclient.h" 3 4 using namespace std; 5 6 // Need to link with Ws2_32.lib 7 //#pragma comment(lib, "ws2_32.lib") 8 SOCKET ConnectSocket; //定义连接Socket,在发送接收时使用 9 /******************************************************* 10 ** 函数名称 : ConnectSer 11 ** 函数功能 : 连接服务器 12 ** 输 入 : 无 13 ** 输 出: 无 14 ** 备 注: 服务器IP:192.168.5.1 PORT:8010 超时连接:1s 15 ********************************************************/ 16 int ConnectSer() 17 { 18 //---------------------- 19 // Initialize Winsock 20 bool ret = false; 21 int error = -1; 22 int len = sizeof(int); 23 WSADATA wsaData; 24 int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 25 if (iResult != NO_ERROR) { 26 ret = false; 27 return ret; 28 } 29 //---------------------- 30 // Create a SOCKET for connecting to server 31 ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 32 if (ConnectSocket == INVALID_SOCKET) { 33 WSACleanup(); 34 ret = false; 35 return ret; 36 } 37 //---------------------- 38 // The sockaddr_in structure specifies the address family, 39 // IP address, and port of the server to be connected to. 40 sockaddr_in clientService; 41 clientService.sin_family = AF_INET; 42 clientService.sin_addr.s_addr = inet_addr("192.168.5.1"); 43 clientService.sin_port = htons(8010); 44 45 //连接超时1秒 46 struct timeval timeout ; 47 fd_set r; 48 unsigned long ul = 1; 49 ioctlsocket(ConnectSocket, FIONBIO,&ul); //设置为非阻塞模式 50 //如果连接失败,则设置超时 51 if(-1 == connect(ConnectSocket, (SOCKADDR *) &clientService, sizeof(clientService) )){ 52 FD_ZERO(&r); 53 FD_SET(ConnectSocket, &r); 54 timeout.tv_sec = 1; //连接超时1秒 55 timeout.tv_usec =0; 56 if( select(0, NULL, &r, NULL, &timeout) > 0 ){ 57 getsockopt(ConnectSocket, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/&len); 58 if(error == 0) 59 ret = true; 60 else 61 ret = false; 62 } 63 else 64 ret = false; 65 } 66 //如果连接成功,返回ret置1 67 else 68 ret = true; 69 ul = 0; 70 ioctlsocket(ConnectSocket, FIONBIO, &ul); //设置为阻塞模式 阻塞时间为timeout时间 71 return ret; 72 }
时间: 2024-11-25 13:04:15