1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <WinSock2.h> #include <stdio.h> #pragma comment(lib,"ws2_32.lib") #define _WINSOCK_DEPRECATED_NO_WARNINGS
int main(void) { WORD wdVersion = MAKEWORD(2,2); WSADATA wdSockMsg; int nRes = WSAStartup(wdVersion,&wdSockMsg); if (nRes != 0) { switch (nRes) { case WSASYSNOTREADY: printf("系统配置问题,重启电脑,检查ws2_32库是否存在,或者是否在环境配置目录下"); break; case WSAVERNOTSUPPORTED: printf("要使用的版本不支持,请更新网络库"); break; case WSAEINPROGRESS: printf("Windows Sockets实现可能限制同时使用它的应用程序的数量"); break; case WSAEPROCLIM: printf("当前函数运行期间,由于某些原因造成阻塞,会返回这个操作码,其他操作均禁止"); break; case WSAEFAULT: printf("参数写错了"); break; } return 0; } if (HIBYTE(wdSockMsg.wVersion) != 2 || LOBYTE(wdSockMsg.wVersion) != 2) { WSACleanup(); return 0; }
SOCKET socketServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (INVALID_SOCKET == socketServer) { WSACleanup(); return 0; } struct sockaddr_in si; si.sin_family = AF_INET; si.sin_port = htons(12345); si.sin_addr.s_addr = htonl(2130706433); int bres = bind(socketServer, (const struct sockaddr *)&si, sizeof(si)); if (SOCKET_ERROR == bres) { int a = WSAGetLastError(); closesocket(socketServer); WSACleanup(); return 0;
} if (SOCKET_ERROR == listen(socketServer, SOMAXCONN)) { int a = WSAGetLastError(); closesocket(socketServer); WSACleanup(); return 0; } struct sockaddr_in clientMsg; int len = sizeof(clientMsg); SOCKET socketClient = accept(socketServer, (struct sockaddr*)&clientMsg, &len); if (INVALID_SOCKET == socketClient) { printf("客户端链接失败\\n"); int a = WSAGetLastError(); closesocket(socketServer); WSACleanup(); return 0; } printf("客户端链接成功\\n"); if (SOCKET_ERROR == send(socketClient, "我是服务器", sizeof("我是服务器"), 0)) { int a = WSAGetLastError(); return 0; }
char buf[1500] = { 0 }; int res = recv(socketClient, buf, 1499, 0); if (res == 0) { printf("链接中断\\n"); } else if (SOCKET_ERROR == res) { int a = WSAGetLastError(); } else { printf("%d %s\\n", res, buf); } closesocket(socketClient); closesocket(socketServer); WSACleanup(); system("pause"); return 0; }
|