Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close connection after reactor.connectTCP in Twisted

Tags:

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 all.
Thanks for your attention and any general advice would be appreciated.
Tony

like image 923
user591415 Avatar asked Feb 25 '23 06:02

user591415


1 Answers

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).

like image 159
Jean-Paul Calderone Avatar answered Apr 08 '23 16:04

Jean-Paul Calderone