代码:
套接字程序,可和本机的服务器互联,不能连接别的服务器,error10057,求大神帮忙!
1 /* TCPClient.cpp -- 用于传递struct */ 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <winsock2.h> 5 #include <string.h> 6 #include <time.h> 7 #include <windows.h> 8 #include <process.h> 9 #include <math.h> 10 #define BUFLEN 2000 // 缓冲区大小 11 #define WSVERS MAKEWORD(2, 0) // 指明版本2.0 12 #pragma comment(lib,"ws2_32.lib") // 指明winsock 2.0 Llibrary 13 14 /*------------------------------------------------------------------------ 15 * main - TCP client for DAYTIME service 16 *------------------------------------------------------------------------*/ 17 18 SOCKET sock, sockets[100] = { NULL }; /* socket descriptor */ // int cc; /* recv character count */ 19 char *packet = NULL; /* buffer for one line of text */ 20 char *pts, *input; 21 HANDLE hThread; 22 unsigned threadID; 23 24 unsigned int __stdcall Chat(PVOID PM) { 25 time_t now; 26 (void)time(&now); 27 pts = ctime(&now); 28 char buf[2000]; 29 while (1) { 30 int cc = recv(sock, buf, BUFLEN, 0); //cc为接收的字符数 31 if (cc == SOCKET_ERROR || cc == 0) { 32 printf("Error: %d ", GetLastError()); 33 printf("与服务器断开连接!\n"); 34 (void)closesocket(sock); 35 break; 36 } 37 else if (cc > 0) { 38 buf[cc] = '\0'; 39 printf("%s\n", buf); 40 } 41 } 42 return 0; 43 } 44 int main(int argc, char *argv[]) { 45 time_t now; 46 (void)time(&now); 47 pts = ctime(&now); 48 //char *host = "192.168.220.1"; /* server IP to connect */ 49 //char *host = "192.168.220.1"; 50 char *host = "202.116.76.22"; 51 char *service = "5050"; /* server port to connect */ 52 struct sockaddr_in sin; /* an Internet endpoint address */ 53 WSADATA wsadata; 54 WSAStartup(WSVERS, &wsadata); /* 启动某版本Socket的DLL */ 55 memset(&sin, 0, sizeof(sin)); 56 sin.sin_family = AF_INET; 57 sin.sin_port = htons((u_short)atoi(service)); //atoi:把ascii转化为int. htons:主机序(host)转化为网络序(network), s--short 58 sin.sin_addr.s_addr = inet_addr(host); //如果host为域名,需要先用函数gethostbyname把域名转化为IP地址 59 sock = socket(PF_INET, SOCK_STREAM, 0); 60 hThread = (HANDLE)_beginthreadex(NULL, 0, Chat, NULL, 0, &threadID); 61 printf(" LET'S CHAT(CLIENT)\n"); 62 connect(sock, (struct sockaddr *)&sin, sizeof(sin)); 63 while (1) { 64 printf("请输入您要发送的信息:\n"); 65 char buf1[2000]; 66 gets_s(buf1); 67 if (!strcmp(buf1, "exit")) 68 goto end; 69 (void)send(sock, buf1, sizeof(buf1), 0); 70 (void)time(&now); 71 pts = ctime(&now); 72 printf("发送成功!\n当前时间:%s\n", pts); 73 } 74 75 end: 76 CloseHandle(hThread); 77 closesocket(sock); 78 WSACleanup(); /* 卸载某版本的DLL */ 79 printf("按回车键继续..."); 80 getchar(); 81 return 0; /* exit */ 82 }
把两台机器的防火墙都关了试试