服务器端代码:#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h> #include <Winsock2.h> #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #pragma comment(lib,"ws2_32.lib") int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return 1; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return 1; } SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); int optval = 1; setsockopt(sockSrv, SOL_SOCKET, SO_REUSEADDR, (const char*)&optval, sizeof(optval)); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); listen(sockSrv, 5); SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); while (1) { SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len); char sendBuf[50]; printf(sendBuf, "Welcome %s to here!", inet_ntoa(addrClient.sin_addr)); send(sockConn, sendBuf, strlen(sendBuf) + 1, MSG_NOSIGNAL); char recvBuf[50]; recv(sockConn, recvBuf, 50, 0); printf("%s\n", recvBuf); closesocket(sockConn); } WSACleanup(); return 0;}
时间: 2024-04-27 20:21:24 浏览: 126
这段代码是一个简单的 TCP 服务器端,它监听本地 6000 端口的连接请求,并对每个连接请求发送欢迎信息,然后等待客户端发送数据,接收客户端发送的数据并打印出来,最后关闭连接。
客户端代码:#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h> #include <Winsock2.h> #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #pragma comment(lib,"ws2_32.lib") int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return 1; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return 1; } SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); char recvBuf[50]; recv(sockClient, recvBuf, 50, 0); printf("%s\n", recvBuf); char sendBuf[50]; sprintf(sendBuf, "Hello, Server!"); send(sockClient, sendBuf, strlen(sendBuf) + 1, MSG_NOSIGNAL); closesocket(sockClient); WSACleanup(); return 0;}
这段代码是一个简单的 TCP 客户端,它连接本地 6000 端口的服务器端,并发送一条问候信息,然后等待服务器端回复,接收服务器端回复并打印出来,最后关闭连接。
当客户端运行后,服务器端会接收到连接请求,并发送欢迎信息给客户端,然后等待客户端发送数据。当客户端发送数据后,服务器端会接收到数据并打印出来。最后客户端和服务器端都关闭连接。
阅读全文