windows 写一个tcp的服务端
时间: 2024-05-03 17:18:51 浏览: 85
C#Tcp服务端
4星 · 用户满意度95%
以下是一个简单的 TCP 服务端的示例代码,用于接收客户端的连接并向客户端发送消息。
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET listenSocket, clientSocket;
struct sockaddr_in serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
int ret;
// 初始化 Winsock
ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (ret != 0) {
printf("WSAStartup() failed with error: %d\n", ret);
return 1;
}
// 创建监听 socket
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET) {
printf("socket() failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 绑定监听 socket 到本地 IP 地址和端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(12345);
ret = bind(listenSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if (ret != 0) {
printf("bind() failed with error: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 开始监听客户端连接
ret = listen(listenSocket, SOMAXCONN);
if (ret != 0) {
printf("listen() failed with error: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
printf("Server is listening on port %d\n", ntohs(serverAddr.sin_port));
// 接受客户端连接并发送消息
clientSocket = accept(listenSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);
if (clientSocket == INVALID_SOCKET) {
printf("accept() failed with error: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
printf("Client connected from %s:%d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
const char* message = "Hello, client!\n";
send(clientSocket, message, strlen(message), 0);
// 关闭 socket
closesocket(clientSocket);
closesocket(listenSocket);
// 清理 Winsock
WSACleanup();
return 0;
}
```
需要注意的是,此代码只适用于 Windows 系统,并且需要链接 `ws2_32.lib` 库。另外,本示例代码省略了错误处理和异常情况的处理,实际应用中需要根据具体情况进行适当的处理。
阅读全文