开发者

How do I detect a lost client connection in a server that inherits from pb.Root?

For example, I have a client that connects to the server with the following:

class MyClientFactory(pb.PBClientFactory, ReconnectingClientFactory):
    def __init__(self):
        pb.PBClientFactory.__init__(self)
        self.ipaddress = No开发者_运维问答ne

    def clientConnectionMade(self, broker):
        log.msg('Started to connect.')
        pb.PBClientFactory.clientConnectionMade(self, broker)

    def buildProtocol(self, addr):
        log.msg('Connected to %s' % addr)
        return pb.PBClientFactory.buildProtocol(self, addr)

    def clientConnectionLost(self, connector, reason):
        log.msg('Lost connection.  Reason:', reason)
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

    def clientConnectionFailed(self, connector, reason):
        log.msg('Connection failed. Reason:', reason)
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

So the client can automatically detect when a connection is lost.

How do I get the same behaviour from the server should a client go down, for example crashing?

I currently catch a DeadReferenceError, (by iterating through a list of potentially connected clients) but that is a non-event driven way - and frankly too late.

Any ideas welcome.

Thanks in advance.

Ben


You can register a callback to be invoked when the connection is lost. There are two APIs for this, one is Broker.notifyOnDisconnect, the other is RemoteReference.notifyOnDisconnect. They do the same thing, but one or the other might be more convenient to access depending on the details of your application.

I'm not sure if you can use this to guarantee that you'll never get DeadReferenceError (for example, I'm not sure what happens if a remote_foo method if yours is invoked, you return a Deferred, the connection is lost, and then the Deferred fires), but you can at least drastically reduce the possibility in the common case (ie, you should be able to always avoid getting DeadReferenceError from callRemote if you never use callRemote after notifyOnDisconnect calls back your function).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜