代码示例:在Windows中用C++完成TCP服务端接收到特定字符串,主函数执行相应命令
时间: 2024-05-04 14:15:35 浏览: 106
可以使用以下代码示例在Windows中用C完成TCP服务端接收到特定字符串,主函数执行相应命令:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET serverSock;
SOCKET clientSock;
struct sockaddr_in sin;
int port = 8888; // 服务端口号
char recvBuf[1024] = {0}; // 接收缓冲区
char respBuf[1024] = {0}; // 响应缓冲区
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("Failed to initialize Winsock.\n");
return 1;
}
// 创建TCP套接字
serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSock == INVALID_SOCKET) {
printf("Failed to create socket.\n");
WSACleanup();
return 1;
}
// 绑定端口
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(serverSock, (struct sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR) {
printf("Failed to bind socket.\n");
closesocket(serverSock);
WSACleanup();
return 1;
}
// 开始监听
if (listen(serverSock, SOMAXCONN) == SOCKET_ERROR) {
printf("Failed to listen on socket.\n");
closesocket(serverSock);
WSACleanup();
return 1;
}
printf("TCP server is running on port %d...\n", port);
// 等待连接
while (1) {
clientSock = accept(serverSock, NULL, NULL);
if (clientSock == INVALID_SOCKET) {
printf("Failed to accept client.\n");
continue;
}
// 接收数据
memset(recvBuf, 0, sizeof(recvBuf));
if (recv(clientSock, recvBuf, sizeof(recvBuf) - 1, 0) == SOCKET_ERROR) {
printf("Failed to receive data from client.\n");
closesocket(clientSock);
continue;
}
// 判断收到的字符串是否为特定字符串
if (strcmp(recvBuf, "special string") == 0) {
// 执行相应命令
printf("Received command: do something.\n");
strcpy(respBuf, "Command executed.");
} else {
strcpy(respBuf, "Invalid command.");
}
// 发送响应数据
if (send(clientSock, respBuf, strlen(respBuf), 0) == SOCKET_ERROR) {
printf("Failed to send response to client.\n");
closesocket(clientSock);
continue;
}
printf("Response sent to client: %s\n", respBuf);
// 关闭连接
closesocket(clientSock);
}
// 关闭套接字
closesocket(serverSock);
// 终止Winsock
WSACleanup();
return 0;
}
```
上述代码创建了一个TCP服务端,监听端口为8888。当服务端接收到客户端发送的字符串为“special string”时,服务端会执行相应命令,并将响应发送给客户端。其他字符串会被视为无效命令。
阅读全文