如何快速搭建一个Linux聊天室应用程序?

avatar
作者
猴君
阅读量:0
要简单实现一个Linux聊天室程序,你可以使用Python的socket库来创建一个简单的基于TCP的聊天服务器和客户端。以下是一个简单的示例:,,1. 创建一个名为chat_server.py的文件,用于编写聊天服务器代码:,,``python,import socket,import threading,,def handle_client(client_socket):, while True:, message = client_socket.recv(1024), print(f"{client_socket.getpeername()}: {message.decode('utf-8')}"), broadcast(message, client_socket),,def broadcast(message, sender_socket):, for client in clients:, if client != sender_socket:, client.send(message),,server = socket.socket(socket.AF_INET, socket.SOCK_STREAM),server.bind(("0.0.0.0", 12345)),server.listen(5),,print("Server is listening on port 12345..."),,clients = [],,while True:, client_socket, addr = server.accept(), print(f"Accepted connection from {addr}"), clients.append(client_socket), client_thread = threading.Thread(target=handle_client, args=(client_socket,)), client_thread.start(),`,,2. 创建一个名为chat_client.py的文件,用于编写聊天客户端代码:,,`python,import socket,import threading,,def receive_messages(client_socket):, while True:, message = client_socket.recv(1024), print(message.decode('utf-8')),,client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM),client_socket.connect(("127.0.0.1", 12345)),,receive_thread = threading.Thread(target=receive_messages, args=(client_socket,)),receive_thread.start(),,while True:, message = input(), client_socket.send(message.encode('utf-8')),`,,3. 分别运行chat_server.pychat_client.py文件,即可实现简单的Linux聊天室程序。你可以通过运行多个chat_client.py`实例来模拟多个用户进行聊天。

简单实现Linux聊天室程序

如何快速搭建一个Linux聊天室应用程序?

1. 准备工作

1.1 安装必要的软件包

在开始编写聊天室程序之前,确保你的Linux系统已经安装了以下软件包:

gcc (GNU Compiler Collection)

make

可以使用以下命令进行安装:

 sudo apt-get update sudo apt-get install build-essential

1.2 创建项目目录结构

如何快速搭建一个Linux聊天室应用程序?

创建一个名为chatroom的目录,并在其中创建两个子目录:clientserver,这将分别用于存放客户端和服务器的代码。

 mkdir chatroom cd chatroom mkdir client server

2. 编写服务器端代码

2.1 创建服务器主文件

server目录下创建一个名为server.c的文件,并添加以下内容:

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 100 #define MAX_CLNT 256 void error_handling(char *message); void send_msg(char *msg, int client_socket); void remove_clnt(int clnt_sock); int clnt_cnt = 0; int clnt_socks[MAX_CLNT]; char name[MAX_CLNT][BUF_SIZE]; int main(int argc, char *argv[]) {     int serv_sock, clnt_sock;     struct sockaddr_in serv_adr, clnt_adr;     int str_len;     socklen_t clnt_adr_sz;     char msg[BUF_SIZE];     int i;     if (argc != 2) {         printf("Usage: %s <port>\n", argv[0]);         exit(1);     }     serv_sock = socket(PF_INET, SOCK_STREAM, 0);     if (serv_sock == -1) {         error_handling("socket() error");     }     memset(&serv_adr, 0, sizeof(serv_adr));     serv_adr.sin_family = AF_INET;     serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);     serv_adr.sin_port = htons(atoi(argv[1]));     if (bind(serv_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1) {         error_handling("bind() error");     }     if (listen(serv_sock, 5) == -1) {         error_handling("listen() error");     }     while (1) {         clnt_adr_sz = sizeof(clnt_adr);         clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_adr, &clnt_adr_sz);         if (clnt_sock == -1) {             continue;         } else {             printf("Connected client IP: %s \n", inet_ntoa(clnt_adr.sin_addr));         }         for (i = 0; i < clnt_cnt; i++) {             if (clnt_sock == clnt_socks[i]) {                 close(clnt_sock);                 return 0;             }         }         clnt_socks[clnt_cnt++] = clnt_sock;         read(clnt_sock, name[clnt_cnt 1], BUF_SIZE);         sprintf(msg, "%s has entered the chat room.", name[clnt_cnt 1]);         for (i = 0; i < clnt_cnt; i++) {             send_msg(msg, clnt_socks[i]);         }     }     close(serv_sock);     return 0; } void error_handling(char *message) {     fputs(message, stderr);     fputc('\n', stderr);     exit(1); } void send_msg(char *msg, int client_socket) {     write(client_socket, msg, strlen(msg)); }

2.2 编译服务器端代码

server目录下,使用以下命令编译服务器端代码:

 gcc -o server server.c

3. 编写客户端代码

如何快速搭建一个Linux聊天室应用程序?

3.1 创建客户端主文件

client目录下创建一个名为client.c的文件,并添加以下内容:

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <pthread.h> #define BUF_SIZE 100 #define NAME_SIZE 20 void *send_msg(void *arg); void *recv_msg(void *arg); void error_handling(char *message); char name[NAME_SIZE] = "[DEFAULT]"; char msg[BUF_SIZE]; int client_socket; pthread_mutex_t mutx; int main(int argc, char *argv[]) {     int str_len;     struct sockaddr_in serv_adr;     pthread_t snd_thread, rcv_thread;     void *thread_return;     if (argc != 4) {         printf("Usage: %s <IP> <port> <name>\n", argv[0]);         exit(1);     }     sprintf(name, "%s", argv[3]);     client_socket = socket(PF_INET, SOCK_STREAM, 0);     if (client_socket == -1) {         error_handling("socket() error");     }     memset(&serv_adr, 0, sizeof(serv_adr));     serv_adr.sin_family = AF_INET;     serv_adr.sin_addr.s_addr = inet_addr(argv[1]);     serv_adr.sin_port = htons(atoi(argv[2]));     if (connect(client_socket, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1) {         error_handling("connect() error");     } else {         puts("Connected...");     }     pthread_mutex_init(&mutx, NULL);     pthread_create(&snd_thread, NULL, send_msg, (void *)&client_socket);     pthread_create(&rcv_thread, NULL, recv_msg, (void *)&client_socket);     pthread_join(snd_thread, &thread_return);     pthread_join(rcv_thread, &thread_return);     close(client_socket);     return 0; } void *send_msg(void *arg) {     int client_socket = *((int *)arg);     char name_msg[NAME_SIZE + BUF_SIZE];     while (1) {         fgets(msg, BUF_SIZE, stdin);         if (!strcmp(msg, "q\n") || !strcmp(msg, "Q\n")) {             close(client_socket);             exit(0);         }         sprintf(name_msg, "%s: %s", name, msg);         pthread_mutex_lock(&mutx);         write(client_socket, name_msg, strlen(name_msg));         pthread_mutex_unlock(&mutx);     }     return NULL; } void *recv_msg(void *arg) {     int client_socket = *((int *)arg);     char message[BUF_SIZE];     int str_len;     while (1) {         str_len = read(client_socket, message, BUF_SIZE 1);         if (str_len == -1) {             return (void *)-1;         }         message[str_len] = '\0';         fputs(message, stdout);     }     return NULL; } void error_handling(char *message) {     fputs(message, stderr);     fputc('\n', stderr);     exit(1); }

3.2 编译客户端代码

client目录下,使用以下命令编译客户端代码:

 gcc -o client client.c -lpthread

4. 运行聊天室程序

小伙伴们,上文介绍了“简单实现linux聊天室程序”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!