要使用Python創建一個多人聊天室,可以借助Socket模塊來實現網絡通信功能。以下是一個簡單的示例代碼:
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()
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())
通過運行以上代碼,就可以創建一個簡單的多人聊天室。用戶可以通過客戶端連接到服務器,并發送消息給其他所有用戶。在服務器端,所有接入的客戶端都會被存儲起來,并在接收到消息時廣播給所有客戶端。