1

为了好玩,我正在用 asynchat 编写一个最小的 IRC 服务器。我正在尝试澄清一些基础知识(我的具体问题遵循代码)。我决定不在 Twisted 中使用任何东西,这样我就可以自己实现更多。首先,我拥有的代码:

import asyncore,asynchat
import socket

class Connection(asynchat.async_chat):
    def __init__(self, server, sock, addr):
        asynchat.async_chat.__init__(self, sock)
        self.set_terminator('\n')
        self.data = ""
        print "client connecting:",addr
        # do some IRC protocol initialization stuff here

    def collect_incoming_data(self, data):
        self.data = self.data + data

    def found_terminator(self):
        print self.data
        self.data = ''

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        conn, addr = self.accept()
        Connection(self, conn, addr)

    def handle_close(self):
        self.close()

s = Server('127.0.0.1',5006)
asyncore.loop()

所以,在我看来,这个代码结构类似于 Twisted 客户端工厂:Server该类被初始化一次,并且基本上Connection每次客户端连接时都会实例化。第一个问题:通过将所有连接存储在列表中来跟踪所有连接的客户端的最佳方法是Server什么?

另外,我不明白如何知道特定客户端何时关闭与我的套接字的连接?Connection实现 asynchat(以及扩展 asyncore),但是Connection当客户端断开连接时,将 handle_close() 回调添加到类中不会触发。它似乎仅适用于服务器上的绑定套接字被破坏时。我没有看到任何用于此目的的方法。无论客户端是否连接,此套接字始终保持打开状态,对吗?

4

1 回答 1

0

要处理客户端关闭的连接,请检查 handle_error 方法,您的客户端是否发出干净的关闭连接?handle_error() :在引发异常且未以其他方式处理时调用。默认版本打印压缩回溯。

希望能帮助到你。

于 2011-12-14T18:51:47.413 回答