使用Linux系统用C语言来编写一个用web服务器构建一个多人聊天室的代码
时间: 2024-03-10 14:50:07 浏览: 95
用C语言编写聊天室
3星 · 编辑精心推荐
以下是基于 Linux 系统用 C 语言编写的一个用 web 服务器构建多人聊天室的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAX_CLIENTS 100
#define MAX_MSG_LEN 1024
#define PORT 8000
int client_sockets[MAX_CLIENTS];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *handle_client(void *arg) {
int client_sock = *((int *)arg);
char msg[MAX_MSG_LEN];
ssize_t bytes_read;
while ((bytes_read = recv(client_sock, msg, MAX_MSG_LEN, 0)) > 0) {
// 广播消息给所有客户端
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; i++) {
if (client_sockets[i] > 0 && client_sockets[i] != client_sock) {
send(client_sockets[i], msg, bytes_read, 0);
}
}
pthread_mutex_unlock(&mutex);
}
// 客户端断开连接
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; i++) {
if (client_sockets[i] == client_sock) {
client_sockets[i] = 0;
break;
}
}
pthread_mutex_unlock(&mutex);
close(client_sock);
pthread_exit(NULL);
}
int main() {
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
pthread_t thread_id;
// 创建 socket
if ((server_sock = 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_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_sock, MAX_CLIENTS) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
// 循环接受客户端连接
while ((client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_addr_len)) > 0) {
// 将客户端 socket 加入数组
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; i++) {
if (client_sockets[i] == 0) {
client_sockets[i] = client_sock;
break;
}
}
pthread_mutex_unlock(&mutex);
// 创建线程处理客户端消息
if (pthread_create(&thread_id, NULL, handle_client, (void *)&client_sock) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
if (client_sock == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
close(server_sock);
exit(EXIT_SUCCESS);
}
```
上述代码通过创建一个 socket,绑定端口,监听端口,循环接受客户端连接的方式来实现聊天室的服务端。客户端连接后,将其 socket 加入数组,然后创建线程处理客户端消息,收到消息后将消息广播给所有客户端。
阅读全文