用c语言写多线程实现网络聊天程序
时间: 2024-02-13 22:01:46 浏览: 90
好的,以下是一个简单的使用 C 语言多线程实现网络聊天程序的示例代码,代码注释中有详细的说明:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define PORT 8888
#define MAX_CLIENTS 5
#define MAX_MESSAGE_SIZE 1024
// 客户端信息结构体
struct client_info {
int sock_fd; // 客户端 socket 文件描述符
struct sockaddr_in addr; // 客户端地址信息
};
// 消息队列
struct message_queue {
char message[MAX_MESSAGE_SIZE];
int sender_sock_fd;
};
int client_count = 0; // 当前连接的客户端数量
struct client_info clients[MAX_CLIENTS]; // 客户端数组
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
struct message_queue message_queue[MAX_CLIENTS * 10]; // 消息队列
int message_count = 0; // 消息队列中的消息数量
// 将消息加入到消息队列中
void add_message_to_queue(char *message, int sender_sock_fd) {
pthread_mutex_lock(&mutex);
if (message_count < MAX_CLIENTS * 10) {
struct message_queue msg;
strncpy(msg.message, message, MAX_MESSAGE_SIZE);
msg.sender_sock_fd = sender_sock_fd;
message_queue[message_count++] = msg;
}
pthread_mutex_unlock(&mutex);
}
// 将消息从消息队列中取出并发送给所有其他客户端
void broadcast_message() {
pthread_mutex_lock(&mutex);
while (message_count > 0) {
struct message_queue msg = message_queue[--message_count];
for (int i = 0; i < client_count; i++) {
if (clients[i].sock_fd != msg.sender_sock_fd) {
send(clients[i].sock_fd, msg.message, strlen(msg.message), 0);
}
}
}
pthread_mutex_unlock(&mutex);
}
// 与客户端进行通信的工作线程函数
void *client_handler(void *arg) {
int sock_fd = *(int *)arg;
char buffer[MAX_MESSAGE_SIZE];
int nbytes;
// 接收客户端发送的消息并转发给其他客户端
while ((nbytes = recv(sock_fd, buffer, MAX_MESSAGE_SIZE, 0)) > 0) {
buffer[nbytes] = '\0';
add_message_to_queue(buffer, sock_fd);
broadcast_message();
}
// 客户端断开连接
pthread_mutex_lock(&mutex);
for (int i = 0; i < client_count; i++) {
if (clients[i].sock_fd == sock_fd) {
printf("Client %s:%d disconnected\n", inet_ntoa(clients[i].addr.sin_addr), ntohs(clients[i].addr.sin_port));
for (int j = i; j < client_count - 1; j++) {
clients[j] = clients[j + 1];
}
client_count--;
break;
}
}
pthread_mutex_unlock(&mutex);
close(sock_fd);
pthread_exit(NULL);
}
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
pthread_t threads[MAX_CLIENTS];
// 创建服务器 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
// 设置服务器地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(server_addr.sin_zero), '\0', 8);
// 绑定服务器 socket 和地址信息
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
// 开始监听端口
if (listen(server_fd, MAX_CLIENTS) == -1) {
perror("listen");
exit(1);
}
printf("Server started on port %d\n", PORT);
// 接受客户端连接并创建工作线程
while (1) {
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &sin_size)) == -1) {
perror("accept");
continue;
}
// 如果客户端数量已经达到上限,则拒绝连接
if (client_count >= MAX_CLIENTS) {
printf("Client %s:%d rejected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
close(client_fd);
continue;
}
// 添加客户端信息到数组中,并创建工作线程
clients[client_count].sock_fd = client_fd;
clients[client_count].addr = client_addr;
printf("Client %s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
pthread_create(&threads[client_count], NULL, client_handler, &clients[client_count].sock_fd);
client_count++;
}
close(server_fd);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_ADDR "127.0.0.1"
#define PORT 8888
#define MAX_MESSAGE_SIZE 1024
int main() {
int sock_fd;
struct sockaddr_in server_addr;
char message[MAX_MESSAGE_SIZE];
// 创建客户端 socket
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
// 设置服务器地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
memset(&(server_addr.sin_zero), '\0', 8);
// 连接服务器
if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
perror("connect");
exit(1);
}
printf("Connected to server %s:%d\n", SERVER_ADDR, PORT);
// 发送消息给服务器
while (1) {
printf("Enter message: ");
fgets(message, MAX_MESSAGE_SIZE, stdin);
send(sock_fd, message, strlen(message) - 1, 0);
}
close(sock_fd);
return 0;
}
```
请注意,这仅是一个简单的示例代码,可以作为实现多线程网络聊天程序的参考。在实际应用中,还需要考虑更多的细节问题,如线程安全、内存管理、异常处理等。
阅读全文