你记得到我给你的服务器端代码吗
时间: 2024-03-05 21:51:06 浏览: 98
石器时代服务器端源代码
4星 · 用户满意度95%
是的,我记得你给我看过一个服务器端代码,大概是这样的:
```
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <stdio.h>
#include <Winsock2.h>
#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);
SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_port = htons(6000);
bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
listen(sockSrv, 5);
printf("Server started.\n");
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while (1) {
SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);
printf("Accepted a client: %s:%d\n", inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port));
char recvBuf[50];
while (1) {
int nRet = recv(sockConn, recvBuf, 50, 0);
if (nRet <= 0) break;
printf("Received message: %s\n", recvBuf);
send(sockConn, recvBuf, strlen(recvBuf) + 1, 0);
}
closesocket(sockConn);
printf("A client disconnected.\n");
}
closesocket(sockSrv);
WSACleanup();
return 0;
}
```
这段代码是一个简单的TCP服务器程序,用于监听端口并接收客户端的连接请求。一旦有客户端连接上来,服务器会打印出客户端的IP地址和端口号,并通过循环接收客户端发送过来的消息并发送回去。需要注意的是,该代码只能在Windows系统下编译和运行。
阅读全文