实现一个多人聊天程序需要用到 socket 编程,下面是一个基于 Linux 的简易多人聊天程序的实现:
1. 服务器端:
```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 PORT 8080
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
char* message = "Welcome to the chat room!\n";
int clients[MAX_CLIENTS] = {0};
int max_clients = MAX_CLIENTS;
fd_set readfds;
// create server socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// set server socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// bind server socket to address
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// listen for incoming connections
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Waiting for clients to connect...\n");
// main loop
while (1) {
// clear the socket set
FD_ZERO(&readfds);
// add server socket to set
FD_SET(server_fd, &readfds);
// add client sockets to set
for (int i = 0; i < MAX_CLIENTS; i++) {
// check if valid socket descriptor
if (clients[i] > 0) {
FD_SET(clients[i], &readfds);
}
}
// wait for activity on any socket
if (select(FD_SETSIZE, &readfds, NULL, NULL, NULL) < 0) {
perror("select failed");
exit(EXIT_FAILURE);
}
// activity on server socket, new client connection
if (FD_ISSET(server_fd, &readfds)) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// add new client to array of clients
for (int i = 0; i < MAX_CLIENTS; i++) {
if (clients[i] == 0) {
clients[i] = new_socket;
break;
}
}
// send welcome message to new client
send(new_socket, message, strlen(message), 0);
printf("New client connected, socket fd is %d, ip is : %s, port : %d\n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
}
// activity on client sockets, incoming message
for (int i = 0; i < MAX_CLIENTS; i++) {
int sd = clients[i];
if (FD_ISSET(sd, &readfds)) {
if ((valread = read(sd, buffer, BUFFER_SIZE)) == 0) {
// client disconnected
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
printf("Client disconnected, socket fd is %d, ip is : %s, port : %d\n", sd, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
close(sd);
clients[i] = 0;
} else {
// broadcast message to all clients except sender
for (int j = 0; j < MAX_CLIENTS; j++) {
int dest = clients[j];
if (dest != 0 && dest != sd) {
send(dest, buffer, valread, 0);
}
}
}
}
}
}
return 0;
}
```
2. 客户端:
```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 <arpa/inet.h>
#include <netdb.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main(int argc, char const *argv[]) {
int sockfd, valread;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char name[BUFFER_SIZE] = {0};
char message[BUFFER_SIZE] = {0};
// create client socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// set server address
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
perror("inet_pton failed");
exit(EXIT_FAILURE);
}
// connect to server
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// get client name
printf("Enter your name: ");
fgets(name, BUFFER_SIZE, stdin);
name[strcspn(name, "\n")] = '\0';
// send client name to server
send(sockfd, name, strlen(name), 0);
// main loop
while (1) {
// clear message buffer
memset(message, 0, BUFFER_SIZE);
// get user input
printf("%s: ", name);
fgets(message, BUFFER_SIZE, stdin);
message[strcspn(message, "\n")] = '\0';
// send message to server
send(sockfd, message, strlen(message), 0);
// receive message from server
valread = read(sockfd, buffer, BUFFER_SIZE);
printf("Server: %s\n", buffer);
}
return 0;
}
```
这个聊天程序可以支持多个客户端连接到服务器,并在客户端之间进行消息交流。每个客户端都需要输入一个昵称,客户端发送的消息会被服务器转发给所有其他客户端。