在windows中用C++完成以下程序:建立一个TCP主机端函数具备以下功能:当主机端口打开时,向客户端发送“open”字符串。当接收到客户端“ready”字符串后,主程序开始循环运行,当接收到“done"字符串后,主程序结束
时间: 2024-05-08 18:18:06 浏览: 114
以下是一个基本的TCP主机端程序,可以实现上述功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
int main() {
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c, recv_size;
char message[100], reply[100];
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
// 创建套接字
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
// 准备服务器地址
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
// 绑定套接字到端口
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
}
// 监听连接请求
listen(s, 3);
// 等待客户端连接
printf("Waiting for incoming connections...\n");
c = sizeof(struct sockaddr_in);
if ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET) {
printf("Connection accepted from %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
// 发送 "open" 字符串给客户端
strcpy(message, "open");
send(new_socket, message, strlen(message), 0);
// 等待客户端回应
recv_size = recv(new_socket, reply, 100, 0);
if (recv_size > 0) {
reply[recv_size] = '\0';
printf("Received reply from client: %s\n", reply);
// 如果收到 "ready" 字符串,开始循环运行
if (strcmp(reply, "ready") == 0) {
while (1) {
recv_size = recv(new_socket, message, 100, 0);
if (recv_size > 0) {
message[recv_size] = '\0';
printf("Received message from client: %s\n", message);
// 如果收到 "done" 字符串,结束循环
if (strcmp(message, "done") == 0) {
break;
}
}
}
}
}
// 关闭连接
closesocket(new_socket);
}
// 清除Winsock
WSACleanup();
return 0;
}
```
该程序使用了Winsock库,可以在Visual Studio等开发环境下编译运行。需要注意的是,该程序只能处理一个客户端的连接请求,如果需要支持多个客户端同时连接,需要使用多线程等机制。
阅读全文