Search code examples
pythontwisted

twisted - Why does TCP4ServerEndpoint's callback and errback never fire?


The callbacks aren't called, whether we successfully are listening or not. What's going on here?

def server_started(self, data, port):
    log.msg("Server listening on port %s." % (port))

def server_failed(self, data, port):
    log.err("Failed to listen on port %s." % (port), data)
    reactor.stop()

log.startLogging(sys.stdout)

port = 6000
endpoint = TCP4ServerEndpoint(reactor, port)
d = endpoint.listen(MyFactory())
d.addCallback(server_started, port)
d.addErrback(server_failed, port)
reactor.run()

Solution

  • Neither callback nor errback is callable as you've defined them.

    If the connection attempt succeeds, the equivalent of server_started(listeningPortObject, port) will be done. This will fail with a TypeError because server_started is defined as taking three arguments (confusingly, one of them is named self which suggests this should actually be a method of a class, not a free function).

    If the connection attempt fails, the equivalent of server_failed(reason, port) will be done. This will also raise TypeError since server_failed also requires three arguments, not two.

    Either outcome will leave d with an unhandled TypeError waiting for another errback to handle it.