Skip to main content
 首页 » 编程设计

python之使用 asyncio.Protocol 的客户端超时

2025年04月02日17jackei

我一直在写 MUD在 python 中,使用 asyncio.Protocol,但是当用户关闭他们的客户端(通常是终端,因为你通过 telnet 连接)而没有正确断开连接时,我遇到了问题。

服务器不会将用户识别为已断开连接,他们仍留在游戏中。

该问题仅在客户端远程连接时出现(出于某种原因,也许有人可以解释......)从本地主机连接时不会发生。

是否有一种巧妙的方法来检查用户是否仍然实际连接(无需额外的客户端软件),或者在失败时如何合并超时?

我的协议(protocol)目前看起来像这样:

class User(Protocol): 
 
    def connection_made(self, transport): 
        self.transport = transport 
        self.addr = transport.get_extra_info('peername') 
        self.authd = False 
        self.name = None 
        self.admin = False 
        self.room = None 
        self.table = None 
        self.db = None 
 
        self.flags = [] 
 
        print("Connected: {}".format(self.addr)) 
        server.connected.append(self) 
 
        actions['help'](self, ['welcome']) 
        self.get_prompt() 
 
    def data_received(self, data): 
        msg = data.decode().strip() 
        args = msg.split() 
 
        if self.authd is False: 
            actions['login'](self, args) 
            return 
 
        if msg: 
            if args[0] in self.db.aliases: 
                args[0] = str(self.db.aliases[args[0]]) 
                msg = ' '.join(args) 
                args = msg.split() 
 
            if msg[0] in server.channels: 
                ch = db.session.query(db.models.Channel).get(msg[0]) 
                if msg[1] =='@': 
                    channels.send_to_channel(self, ch, msg[2:], do_emote=True) 
                else: 
                    channels.send_to_channel(self, ch, msg[1:]) 
                self.get_prompt() 
                return 
 
            if args[0] in actions: 
                if self.is_frozen(): 
                    self.send_to_self("You're frozen solid!") 
                else: 
                    actions[args[0]](self, args[1:] if len(args) > 1 else None) 
                self.get_prompt() 
                return 
            self.send_to_self("Huh?") 
        else: 
            if self.table is not None: 
                actions['table'](self, None) 
            elif self.room is not None: 
                actions['look'](self, None) 
 
    def send_to_self(self, msg): 
        msg = "\r\n" + msg 
        msg = colourify(msg) 
        self.transport.write(msg.encode()) 
 
    @staticmethod 
    def send_to_user(user, msg): 
        msg = "\r\n"+msg 
        msg = colourify(msg) 
        user.transport.write(msg.encode()) 
 
    @staticmethod 
    def send_to_users(users, msg): 
        msg = "\r\n"+msg 
        msg = colourify(msg) 
        for user in users: 
            user.transport.write(msg.encode()) 
 
    def connection_lost(self, ex): 
        print("Disconnected: {}".format(self.addr)) 
        server.connected.remove(self) 
 
        if self.authd: 
            self.save() 
            server.users.remove(self) 
            self.room.occupants.remove(self) 

注意:我已经切掉了很多多余的东西。如果你想要完整的代码,它是 here.

请您参考如下方法:

您可以在每次 data_received() 调用时安排一个新的超时处理程序(当然要取消之前的超时处理程序)。我发现这种方法太麻烦了。

或者,作为一个选项,切换到 asyncio streams -- 您可以使用 asyncio.wait_for 或尚未发布的全新 asyncio.timeout。