要用C语言编写聊天软件,你需要掌握网络编程的基本知识,特别是套接字编程。以下是一个简单的TCP聊天室服务器端和客户端的示例代码,展示了如何使用C语言实现基本的聊天功能:
服务器端代码 (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)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // 配置服务器地址 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)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // 监听连接 if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } while (1) { // 接受客户端连接 client_addr_size = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&client_addr_size); if (client_fd < 0) { 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)