linux简单聊天室程序生成代码
时间: 2023-12-02 09:04:52 浏览: 93
以下是一个简单的 Linux 聊天室程序的生成代码,其中使用了 socket 和 pthread 库:
server.c
```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 PORT 8888
#define MAX_CLIENTS 100
int clients[MAX_CLIENTS];
int num_clients = 0;
void *handle_client(void *arg) {
int client_fd = *(int *) arg;
char buffer[1024];
while (1) {
memset(buffer, 0, sizeof(buffer));
if (read(client_fd, buffer, sizeof(buffer)) <= 0) {
printf("Client %d disconnected\n", client_fd);
break;
}
printf("Received message from client %d: %s", client_fd, buffer);
for (int i = 0; i < num_clients; i++) {
if (clients[i] != client_fd) {
write(clients[i], buffer, strlen(buffer));
}
}
}
for (int i = 0; i < num_clients; i++) {
if (clients[i] == client_fd) {
clients[i] = clients[num_clients - 1];
num_clients--;
break;
}
}
close(client_fd);
return NULL;
}
int main(int argc, char *argv[]) {
int server_fd, client_fd;
struct sockaddr_in server, client;
pthread_t thread;
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *) &server, sizeof(server)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 5) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Server started\n");
while (1) {
socklen_t client_len = sizeof(client);
if ((client_fd = accept(server_fd, (struct sockaddr *) &client, &client_len)) == -1) {
perror("accept");
continue;
}
if (num_clients == MAX_CLIENTS) {
printf("Maximum number of clients reached\n");
close(client_fd);
continue;
}
clients[num_clients++] = client_fd;
pthread_create(&thread, NULL, handle_client, (void *) &client_fd);
pthread_detach(thread);
printf("Client %d connected\n", client_fd);
}
return 0;
}
```
client.c
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8888
int main(int argc, char *argv[]) {
int server_fd;
struct sockaddr_in server;
char buffer[1024];
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(SERVER_IP);
server.sin_port = htons(PORT);
if (connect(server_fd, (struct sockaddr *) &server, sizeof(server)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
printf("Connected to server\n");
while (1) {
fgets(buffer, sizeof(buffer), stdin);
if (write(server_fd, buffer, strlen(buffer)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
return 0;
}
```
以上代码可以在 Linux 系统下编译运行,实现一个简单的聊天室程序。
阅读全文