Twisted报错:builtins.TypeError: Echo.connectionLost() takes 1 positional argument

90 阅读1分钟

问题代码

我的python代码如下:

from twisted.internet import reactor, protocol

# 搭建一个简单的回声服务器

class Echo(protocol.Protocol):
    # 接收到数据时候的处理
    def dataReceived(self, data):
        self.transport.write("I got it!".encode('utf-8'))

    def connectionLost(self):
        print("连接已断开")

def main():
    factory = protocol.Factory()
    factory.protocol = Echo
    reactor.listenTCP(1233, factory)
    reactor.run()

if __name__ == '__main__':
    main()

原因

点进去Protocol一看

        def connectionLost(self, reason: failure.Failure = connectionDone) -> None:
        """
        Called when the connection is shut down.

        Clear any circular references here, and any external references
        to this Protocol.  The connection has been closed.

        @type reason: L{twisted.python.failure.Failure}
        """

才发现我们在重写connectionLost的时候,需要给函数两个参数,我少了一个参数reason

下面是修改之后的代码

from twisted.internet import reactor, protocol

# 搭建一个简单的回声服务器


class Echo(protocol.Protocol):
    # 接收到数据时候的处理
    def dataReceived(self, data):
        self.transport.write("I got it!".encode('utf-8'))

-    def connectionLost(self):
-       print("连接已断开")

+    def connectionLost(self, reason):
+        print("连接已断开", reason)

def main():
    factory = protocol.Factory()
    factory.protocol = Echo
    reactor.listenTCP(1233, factory)
    reactor.run()


if __name__ == '__main__':
    main()