在C语言中实现对话程序,通常需要结合网络编程和用户输入输出。以下是一个简单的TCP聊天程序示例,包括服务器端和客户端代码,以及一个基本的对话管理系统设计。
简单的TCP聊天程序示例
服务器端代码 (server.c)
```c
include include include include include include define PORT 8080 define BUFFER_SIZE 1024 int main() { int server_fd, client_fd; struct sockaddr_in server_addr, client_addr; socklen_t client_addr_size; char buffer[BUFFER_SIZE]; // 创建套接字 if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(EXIT_FAILURE); } // 配置套接字 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(PORT); // 绑定套接字 if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind"); exit(EXIT_FAILURE); } // 监听连接 if (listen(server_fd, 3) == -1) { perror("listen"); exit(EXIT_FAILURE); } while (1) { // 接受客户端连接 client_addr_size = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_size); if (client_fd == -1) { perror("accept"); continue; } // 读取并输出客户端消息 read(client_fd, buffer, BUFFER_SIZE); printf("Received from client: %s\n", buffer); // 向客户端发送消息 send(client_fd, "Message received", strlen("Message received"), 0); printf("Sent to client: Message received\n"); // 关闭客户端套接字 close(client_fd); } // 关闭服务器套接字 close(server_fd); return 0; } ``` 客户端代码 (client.c)