写在前面的絮絮叨叨
运行环境:需安装python3.x和对应python3.x的wxpython库
windows操作系统:pip install wx
Linux操作系统:也可通过pip下载wxpython,进入https://extras.wxpython.org/wxPython4/extras/linux/gtk3/选择相对应操作系统的wxpython.whl进行下载
踩过的坑:假如安装wxpython之后运行代码还是报错:No model named “wx”,就检查一下所安装的wxpython是否是支持python3.x的
项目代码
不带注释总代码行在200行左右,已上传至github:https://github.com/atuo-200/chat_room
server.py
import asynchat
import asyncore
import time
# 定义端口
PORT = 6666
# 定义结束异常类
class EndSession(Exception):
pass
class ChatServer(asyncore.dispatcher):
"""
创建一个支持多用户连接的聊天服务器
"""
#重写构造方法
def __init__(self, port):
#显式调用父类构造方法
asyncore.dispatcher.__init__(self)
# 创建socket
self.create_socket()
# 设置 socket 为可重用
self.set_reuse_addr()
# 监听端口
self.bind(('', port))
#设置最大连接数为5,超出排队
self.listen(5)
self.users = {
}
self.main_room = ChatRoom(self)
def handle_accept(self):
#阻塞式监听,等待客户端的连接,生成连接对象(SSL通道,客户端地址)
conn, addr = self.accept()
#建立会话
ChatSession(self, conn)
class ChatSession(asynchat.async_chat):
"""
负责和客户端通信的会话类
"""
def __init__(self, server, sock):
asynchat.async_chat.__init__(self, sock)
self.server = server
#设置数据终止符
self.set_terminator(b'\n')
#设置数据列表
self.data = []
self.name = None
self.enter(LoginRoom(server))
def enter(self, room):
# 从当前房间移除自身,然后添加到指定房间
try:
cur = self.room
except AttributeError:
pass
else:
cur.remove(self)
self.room = room
room.add(self)
#重写处理客户端发来数据的方法
def collect_incoming_data(self, data):
# 接收客户端的数据并解码
self.data.append(data.decode("utf-8"))
#重写发现数据中终止符号时的处理方法
def found_terminator(self):
#将数据列表中的内容整合为一行
line = ''.join(self.data)
#清理数据列表
self.data = []
try:
self.room.handle(self, line.encode("utf-8"))
# 退出聊天室的处理
except EndSession:
self.handle_close()
def handle_close(self):
# 当 session 关闭时,将进入 LogoutRoom
asynchat.async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))

本文介绍了一个基于Python的多人在线文字聊天室的实现方法,利用asyncore和asynchat模块完成异步通信,以及使用wxPython构建GUI界面。聊天室包括用户登录、消息广播和在线用户查看等功能。
最低0.47元/天 解锁文章
404





