基于Python guI的多人聊天室的设计与实现
由于原代码较长,以下是一个简化版本的聊天室服务器代码实例,展示了如何使用Python的socket
和threading
库来创建一个基本的多人聊天室服务器。
import socket
import threading
# 聊天室服务器
class ChatServer:
def __init__(self, host, port):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((host, port))
self.server_socket.listen(5)
print(f"Chat server started on {host}:{port}")
self.clients = []
def broadcast(self, message, sender_name):
for client in self.clients:
if client != sender_name:
client.send(f"{sender_name} says: {message}".encode('utf-8'))
def start_listening(self):
while True:
client_socket, address = self.server_socket.accept()
client_name = client_socket.recv(1024).decode('utf-8')
print(f"{client_name} has joined the chat")
client_socket.send(f"Welcome to the chat, {client_name}".encode('utf-8'))
self.broadcast(f"{client_name} has joined the chat", client_name)
self.clients.append(client_name)
client_thread = threading.Thread(target=self.listen_to_client, args=(client_socket, client_name))
client_thread.start()
def listen_to_client(self, client_socket, client_name):
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
if message == 'exit':
self.clients.remove(client_name)
client_socket.close()
break
self.broadcast(message, client_name)
except ConnectionResetError:
self.clients.remove(client_name)
client_socket.close()
self.broadcast(f"{client_name} has left the chat", client_name)
break
# 运行服务器
if __name__ == "__main__":
host = '127.0.0.1'
port = 8080
server = ChatServer(host, port)
server.start_listening()
这段代码创建了一个简单的聊天室服务器,它能够接受多个客户端的连接,并将消息广播给所有在线的客户端。服务器使用socket
库来处理网络通信,并使用threading
库来为每个客户端启动一个新线程,以便消息的接收和发送可以并行进行。这个简化版本的服务器没有实现图形用户界面,但它展示了服务器端的核心逻辑。
评论已关闭