开发者

How to close connection after reactor.connectTCP in Twisted

I wanted to ask a question on how to close the connection in twisted RPC.

I know a similar question was asked but it doesn't seem to answer mine.

I am doing some basic connection as sketched below:

cfactory = pb.PBClientFactory()
reactor.connectTCP(<host>, <port>, cfactory)
dfr.addCallbacks(<callback>, <errfun>, ...)
...
(in the <callback> func)   remote.callRemote('myfunc', ...)

It all works and does the stuff I need.

But the trouble is that I see the connection still active ("ESTABLISHED") if I check it by netstat -a.

Since I'm doing this between a client and a server that run indefinitely, I cannot just keep accumulating the active connections.

I can't stop the reactor either for the same reason.

So, is there a way to close the connection, short of going through creating one's own protocol?

I wanted to check first since it is all in working order except this one fact - If possible I'll just add the one needed thing rather than starting with protocol setup and al开发者_如何学运维l.

Thanks for your attention and any general advice would be appreciated.

Tony


remote is a RemoteReference. It has a broker attribute which is the twisted.spread.pb.Broker protocol instance that created it. Like almost all protocols, the Broker instance has a transport attribute which refers to the object representing the connection the protocol is running over.

Therefore, remote.broker.transport.loseConnection() should do what you want.

There are other options, too. You could capture the Broker instance at the factory:

class MyPBFactory(pb.PBClientFactory):
    def buildProtocol(self, addr):
        proto = pb.PBClientFactory.buildProtocol(self, addr)
        self.proto = proto
        return proto

Now you have a proto attribute on the factory (but only after the connection actually gets made, and nothing will clean it up so it will still be there after the connection is lost - but you could take care of that).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜