router startup error: listening on same port detection

#1

I am going through and adding proper error detection ti my code. One of the errors I ran in to with my customer router is something is already listening on the address. In other words, I am trying to start my router and the router was already running. I am still learning all of this twisted/autobahn protocol, the answer was not intuitive to me so I though I’d post it here for others:

## start the server from an endpoint
···
##
## this address clash detection was a goody I got from stackoverflow:
## http://stackoverflow.com/questions/12007316/exiting-twisted-application-after-listenfailure

server = serverFromString(reactor, args.endpoint)
def listen():
    srv = server.listen(transport_factory)
    def ListenFailed(reason):
        log.msg("On Startup Listen Failed with {}".format(reason))
        reactor.stop()
    srv.addErrback(ListenFailed)

reactor.callWhenRunning(listen)
reactor.run()

``

I guess when the server.listen() is called it sets up a deferred which in turn listens, it doesn’t do it when called. So a twisted errback is needed to catch the error when this happens. I initially put the Errback inline, like this:

server = serverFromString(reactor, args.endpoint)
srv = server.listen(transport_factory)
def ListenFailed(reason):
    log.msg("On Startup Listen Failed with {}".format(reason))
    reactor.stop()
    sys.exit(42)
srv.addErrback(ListenFailed)

reactor.run()

``

my ‘On Startup’ message was logged, but the program still just hung there and didn’t exit. Maybe it will be useful for somebody else :slight_smile:

-g

0 Likes