#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #define MAX_CLIENTS 10 #define BUFFER_SIZE 1024 int client_sockets[MAX_CLIENTS]; pthread_t threads[MAX_CLIENTS]; int num_clients = 0; void *client_handler(void *arg) { int client_socket = *(int *)arg; char buffer[BUFFER_SIZE]; while(1) { int recv_len = recv(client_socket, buffer, BUFFER_SIZE, 0); if(recv_len == -1) { perror("recv"); break; } if(recv_len == 0) { printf("Client disconnected\n"); break; } buffer[recv_len] = '\0'; printf("Received message: %s\n", buffer); for(int i = 0; i < num_clients; i++) { if(client_sockets[i] != client_socket) { send(client_sockets[i], buffer, strlen(buffer), 0); } } } close(client_socket); pthread_exit(NULL); } int main(int argc, char *argv[]) { int server_socket, client_socket; struct sockaddr_in server_addr, client_addr; socklen_t client_len = sizeof(client_addr); int port = 8888; if(argc > 1) { port = atoi(argv[1]); } server_socket = socket(AF_INET, SOCK_STREAM, 0); if(server_socket == -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 = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if(bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind"); exit(EXIT_FAILURE); } if(listen(server_socket, MAX_CLIENTS) == -1) { perror("listen"); exit(EXIT_FAILURE); } printf("Server started on port %d\n", port); while(1) { client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len); if(client_socket == -1) { perror("accept"); continue; } printf("New client connected: %s\n", inet_ntoa(client_addr.sin_addr)); if(num_clients >= MAX_CLIENTS) { printf("Reached maximum number of clients\n"); close(client_socket); continue; } client_sockets[num_clients] = client_socket; pthread_create(&threads[num_clients], NULL, client_handler, (void *)&client_socket); num_clients++; } close(server_socket); return 0; }
时间: 2024-04-28 21:19:12 浏览: 171
mysql的udf编程之非阻塞超时重传
这是一个使用 C 语言编写的简单的多客户端聊天室服务器程序。它使用了 TCP 协议和 POSIX 线程库。服务器监听指定端口,当客户端连接进来时,它会创建一个新的线程处理该客户端的消息。每当一个客户端发送消息时,服务器会将该消息广播给所有其他客户端。
客户端连接上服务器后,可以发送消息给其他客户端。服务器会将该消息广播到所有其他连接的客户端,使得所有客户端都能看到这个消息。当客户端关闭连接时,服务器会将该客户端从客户端列表中去除。
该程序还有一些限制,例如最多只支持 10 个客户端同时连接,如果达到了这个限制,新的客户端连接会被拒绝。
阅读全文