要在C語言中實現一個網絡聊天室,你需要使用套接字編程(socket programming)和多線程或多進程。以下是一個簡單的實現步驟:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int client_sockets[100];
int client_count = 0;
pthread_mutex_t lock;
void *handle_client(void *arg);
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_size;
// 創建套接字
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket");
exit(1);
}
// 配置服務器地址
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_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(1);
}
// 監聽連接
if (listen(server_fd, 100) == -1) {
perror("listen");
exit(1);
}
pthread_mutex_init(&lock, NULL);
printf("Server is running on port %d\n", PORT);
while (1) {
client_addr_size = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_fd == -1) {
perror("accept");
continue;
}
pthread_t thread;
pthread_create(&thread, NULL, handle_client, (void *)client_fd);
pthread_detach(thread);
}
close(server_fd);
return 0;
}
void *handle_client(void *arg) {
int client_fd = (int)arg;
char buffer[BUFFER_SIZE];
while (1) {
ssize_t received = recv(client_fd, buffer, BUFFER_SIZE, 0);
if (received <= 0) {
break;
}
pthread_mutex_lock(&lock);
for (int i = 0; i< client_count; i++) {
if (client_sockets[i] != client_fd) {
send(client_sockets[i], buffer, received, 0);
}
}
pthread_mutex_unlock(&lock);
}
pthread_mutex_lock(&lock);
for (int i = 0; i< client_count; i++) {
if (client_sockets[i] == client_fd) {
client_sockets[i] = client_sockets[client_count - 1];
client_count--;
break;
}
}
pthread_mutex_unlock(&lock);
close(client_fd);
return NULL;
}
gcc server.c -o server -lpthread
./server
創建一個客戶端程序,用于連接到服務器并發送/接收消息。客戶端程序的實現與上述服務器程序類似,但不需要監聽和接受連接。你可以使用 connect()
函數連接到服務器,然后使用 send()
和 recv()
函數發送和接收消息。
編譯并運行客戶端:
gcc client.c -o client
./client
現在你可以運行多個客戶端實例,它們將能夠在聊天室中發送和接收消息。請注意,這個示例僅用于演示目的,實際應用中可能需要考慮更多的錯誤處理和功能。