标签:
服务端:
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <stdio.h> 4 #include <winsock2.h> 5 #pragma comment (lib, "ws2_32.lib") 6 7 /* 8 TCP服务端 9 */ 10 int main(void) 11 { 12 int len = 0; 13 WSADATA wd; 14 int ret = 0; 15 SOCKET s, c; 16 char sendBuf[1000] = "", recvBuf[1000] = ""; 17 SOCKADDR_IN saddr, caddr; 18 ret = WSAStartup(MAKEWORD(2, 2), &wd); /*1.初始化操作*/ 19 20 if (ret != 0) 21 { 22 return 0; 23 } 24 if (HIBYTE(wd.wVersion) != 2 || LOBYTE(wd.wVersion) != 2) 25 { 26 printf("初始化失败"); 27 WSACleanup(); 28 return 1; 29 } 30 31 /*2.创建服务端socket*/ 32 s = socket(AF_INET, SOCK_STREAM, 0); 33 34 /*3.设置服务端信息*/ 35 saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); 36 saddr.sin_family = AF_INET; /*协议类型*/ 37 saddr.sin_port = htons(8888); 38 39 /*4.绑定在本地端口*/ 40 bind(s, (SOCKADDR *)&saddr, sizeof(SOCKADDR)); 41 42 /*5.监听端口*/ 43 listen(s, 5); 44 45 len = sizeof(SOCKADDR); 46 47 while (1) 48 { 49 /*6.等待客户端连接,会阻塞在此处,直到有客户端连接到来。*/ 50 c = accept(s, (SOCKADDR*)&caddr, &len); 51 52 sprintf(sendBuf, "欢迎来到我的第一个socket,您的ip地址为:%s\n", inet_ntoa(caddr.sin_addr)); 53 54 /*7.发送数据到客户端*/ 55 send(c, sendBuf, strlen(sendBuf) + 1, 0); 56 57 /*8.接受客户端的返回*/ 58 recv(c, recvBuf, 1000, 0); 59 60 /*9.打印出客户端发送来的数据*/ 61 printf("%s\n", recvBuf); 62 63 /*10.如果不再跟这个客户端联系,就关闭它*/ 64 closesocket(c); 65 } 66 /*如果有退出循环的条件,这里还需要清除对socket库的使用*/ 67 /* WSACleanup();*/ 68 return 0; 69 }
客户端:
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <stdio.h> 4 #include <winsock2.h> 5 #pragma comment (lib, "ws2_32.lib") 6 7 int main(void) 8 { 9 WSADATA wd; 10 int ret = 0; 11 SOCKET c; 12 char recvBuf[1000] = "", sendBuf[1000] = ""; 13 SOCKADDR_IN saddr; 14 ret = WSAStartup(MAKEWORD(2, 2), &wd); /*1.初始化操作*/ 15 16 if (ret != 0) 17 { 18 return 0; 19 } 20 21 if (HIBYTE(wd.wVersion) != 2 || LOBYTE(wd.wVersion) != 2) 22 { 23 printf("初始化失败"); 24 WSACleanup(); 25 return 1; 26 } 27 28 /*2.创建客户端socket*/ 29 c = socket(AF_INET, SOCK_STREAM, 0); 30 31 /*3.定义要连接的服务端信息*/ 32 saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); 33 saddr.sin_family = AF_INET; 34 saddr.sin_port = htons(8888); 35 36 /*4.连接服务端*/ 37 connect(c, (SOCKADDR*)&saddr, sizeof(SOCKADDR)); 38 recv(c, recvBuf, 1000, 0); 39 printf("服务端发来的数据:%s\n", recvBuf); 40 41 sprintf(sendBuf, "服务端你好!!!"); 42 send(c, sendBuf, strlen(sendBuf) + 1, 0); 43 44 closesocket(c); 45 WSACleanup(); 46 47 getchar(); 48 return 0; 49 }
标签:
原文地址:http://www.cnblogs.com/huxc/p/4272940.html