怎么用Python打造一个多人聊天室

avatar
作者
猴君
阅读量:0

要使用Python创建一个多人聊天室,可以借助Socket模块来实现网络通信功能。以下是一个简单的示例代码:

  1. 创建服务器端代码:
import socket import threading  # 服务器端IP和端口 SERVER_HOST = '0.0.0.0' SERVER_PORT = 8888  # 用于存储客户端连接 clients = []  def handle_client(client_socket):     while True:         try:             message = client_socket.recv(1024).decode()             print(message)             broadcast(message, client_socket)         except:             clients.remove(client_socket)             client_socket.close()             break  def broadcast(message, client_socket):     for client in clients:         if client != client_socket:             try:                 client.send(message.encode())             except:                 client.close()                 clients.remove(client)  # 创建服务器Socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((SERVER_HOST, SERVER_PORT)) server_socket.listen(5)  print(f"Server is running on {SERVER_HOST}:{SERVER_PORT}")  while True:     client_socket, client_address = server_socket.accept()     clients.append(client_socket)     print(f"{client_address} connected")      client_thread = threading.Thread(target=handle_client, args=(client_socket,))     client_thread.start() 
  1. 创建客户端代码:
import socket import threading  # 服务器端IP和端口 SERVER_HOST = '127.0.0.1' SERVER_PORT = 8888  def receive_messages(client_socket):     while True:         try:             message = client_socket.recv(1024).decode()             print(message)         except:             break  # 创建客户端Socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((SERVER_HOST, SERVER_PORT))  print("Connected to the server")  receive_thread = threading.Thread(target=receive_messages, args=(client_socket,)) receive_thread.start()  while True:     message = input()     client_socket.send(message.encode()) 

通过运行以上代码,就可以创建一个简单的多人聊天室。用户可以通过客户端连接到服务器,并发送消息给其他所有用户。在服务器端,所有接入的客户端都会被存储起来,并在接收到消息时广播给所有客户端。

广告一刻

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