Search code examples
pythonnetwork-programmingtwistedautobahn

Autobahn: catch sendMessage error


how can I catch sendMessage error ? There is no exception propagation. When the server is down (half-open connection) I want catch the error in my client code. If the server running the websocket daemon crashes, reboots, loses network connectivity closeConnection/ConnectionLost/ConnectionFailed callbacks does not work.

from autobahn.websocket import WebSocketClientProtocol

class ClientProtocol(WebSocketClientProtocol):
    def onOpen(self):
        def heartbeat():
            self.sendMessage("HB")
            self.factory.reactor.callLater(1, heartbeat)

        # I want to catch a socket error   
        try:
            heartbeat()
        except Exception as e:  
            print e

Maybe there are better solutions than this. Ping Pong ? Simply I cannot find a way how my client can detect server crash/reboots then reconnect.

I am using autobahn 0.6.5


Solution

  • Yes, there is a better solution for fast detection of lost connections: WebSocket ping/pong. This is built into the WebSocket protocol.

    AutobahnPython supports automatic WebSocket Ping/Pong, mostly for exact this scenario (fast connection loss detection and connection keep-alive).

    You can activate this using these parameters:

    • autoPingInterval
    • autoPingTimeout
    • autoPingSize

    which can be set for both servers and clients.

    You will need a recent AutobahnPython version (0.9.4+ I think). Yours (0.6.5) does not have that feature.