Windows 环境下用c语言实现TCP服务器
时间: 2023-05-14 17:04:13 浏览: 109
用C语言做的TCP程序
4星 · 用户满意度95%
可以使用Winsock库来实现TCP服务器。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(27015);
iResult = bind(listenSocket, (SOCKADDR*)&service, sizeof(service));
if (iResult == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
iResult = listen(listenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
printf("Waiting for client to connect...\n");
SOCKET clientSocket = accept(listenSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 1;
}
printf("Client connected!\n");
char recvbuf[512];
int recvbuflen = 512;
iResult = recv(clientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Received %d bytes: %s\n", iResult, recvbuf);
} else if (iResult == 0) {
printf("Connection closing...\n");
} else {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
iResult = shutdown(clientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
这个代码创建了一个TCP服务器,监听端口27015。当客户端连接上来后,服务器会接收客户端发送的数据,并打印出来。然后服务器会关闭连接。注意,这个代码只是一个简单的示例,实际应用中还需要进行错误处理和安全性检查。
阅读全文