帮我在windows中用C++写一个TCP主机通讯代码
时间: 2024-05-02 22:19:00 浏览: 99
当然可以!以下是一个简单的TCP主机通讯代码示例,你可以在Windows中用C语言进行编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8080
int main() {
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
struct sockaddr_in serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[1024];
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed: %d\n", WSAGetLastError());
return 1;
}
// 创建套接字
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("socket failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 绑定端口号
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(PORT);
if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
// 监听连接请求
if (listen(serverSocket, 5) == SOCKET_ERROR) {
printf("listen failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
printf("Server listening on port %d...\n", PORT);
// 接受客户端连接
if ((clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrLen)) == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
printf("Client connected: %s:%d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
// 接收和发送数据
while (1) {
memset(buffer, 0, sizeof(buffer));
if (recv(clientSocket, buffer, sizeof(buffer), 0) == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
printf("Received: %s\n", buffer);
if (strcmp(buffer, "quit\n") == 0) {
break;
}
if (send(clientSocket, buffer, strlen(buffer), 0) == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
}
// 关闭套接字和Winsock库
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
return 0;
}
```
这个示例代码实现了一个简单的TCP服务器,它可以监听来自客户端的连接请求,并接收和发送数据。你可以按照这个示例进行修改,以满足你的具体需求。
阅读全文