如何用C语言编写多人聊天室 具备群聊和私聊功能
时间: 2024-04-16 12:26:56 浏览: 173
要编写一个多人聊天室,具备群聊和私聊功能,你可以使用套接字(socket)编程来实现。下面是一个简单的示例代码,可以作为你开始的参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
typedef struct {
int client_socket;
struct sockaddr_in address;
char username[20];
} Client;
Client clients[MAX_CLIENTS];
int num_clients = 0;
void broadcast_message(const char* message, int sender_socket) {
for (int i = 0; i < num_clients; i++) {
if (clients[i].client_socket != sender_socket) {
send(clients[i].client_socket, message, strlen(message), 0);
}
}
}
void handle_client_message(int client_index) {
char buffer[BUFFER_SIZE];
int read_size;
read_size = recv(clients[client_index].client_socket, buffer, BUFFER_SIZE - 1, 0);
if (read_size > 0) {
buffer[read_size] = '\0';
if (buffer[0] == '/') {
// 私聊功能
// 实现私聊功能的逻辑
} else {
// 群聊功能
broadcast_message(buffer, clients[client_index].client_socket);
}
} else if (read_size == 0) {
printf("Client disconnected: %s\n", clients[client_index].username);
close(clients[client_index].client_socket);
// 移除已断开连接的客户端
for (int i = client_index; i < num_clients-1; i++) {
clients[i] = clients[i+1];
}
num_clients--;
}
}
int main() {
int server_socket, new_socket;
struct sockaddr_in server_address, client_address;
socklen_t address_len;
// 创建套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8888);
// 绑定套接字到服务器地址和端口
if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_socket, MAX_CLIENTS) < 0) {
perror("Listen failed");
exit(EXIT_FAILURE);
}
printf("Chat server started on port 8888\n");
while (1) {
// 接受客户端连接请求
address_len = sizeof(client_address);
new_socket = accept(server_socket, (struct sockaddr*)&client_address, &address_len);
if (new_socket < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
// 获取客户端的用户名
char username[20];
read(new_socket, username, sizeof(username));
printf("New connection: %s\n", username);
// 将客户端添加到客户端列表中
Client new_client;
new_client.client_socket = new_socket;
new_client.address = client_address;
strcpy(new_client.username, username);
clients[num_clients++] = new_client;
// 向所有客户端广播新用户加入的消息
char join_message[50];
sprintf(join_message, "%s has joined the chat\n", username);
broadcast_message(join_message, new_socket);
// 创建新的线程来处理客户端消息
// 这里可以使用多线程或多进程来处理并发连接
// 注意:线程/进程的创建和管理需要根据具体的操作系统和编程环境进行
// 这里只提供了基本的逻辑示例
handle_client_message(num_clients - 1);
}
return 0;
}
```
上述代码实现了一个简单的多人聊天室,允许客户端进行群聊和私聊。你可以根据需求进行进一步的修改和扩展。请注意,上述代码中只给出了基本的实现逻辑,实际的实现可能需要更多的错误处理和线程/进程管理。同时,还需要考虑并发连接和消息的同步问题。
阅读全文