How to close a connection after a .connectTCP reactor in Twisted

I wanted to ask a question about how to close a connection in twisted RPC .
I know that a similar question was asked, but it does not seem to answer me.
I am making a basic connection as shown below:

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

Everything works and does what I need.
But the problem is that I see that the connection is still active ("ESTABLISHED") if I check it on netstat -a .
Since I am doing this between a client and a server that has been working indefinitely, I cannot just continue to accumulate active connections.
I cannot stop the reactor for the same reason.
So, is there a way to close the connection without waiting for the creation of its own protocol?
At first I wanted to check, since this is all in working condition, with the exception of this fact. If possible, I’ll just add the right thing, and don’t start by setting up the protocol and all. Thank you for your attention and any general recommendations will be appreciated. Tony

+4
source share
1 answer

remote is RemoteReference . It has the broker attribute, which is an instance of the twisted.spread.pb.Broker protocol that created it. Like almost all protocols, a broker instance has a transport attribute that refers to an object that represents the connection in which the protocol runs.

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

There are other options. You can grab a broker instance in the factory:

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

Now you have the proto attribute on the factory (but only after the connection is really made and nothing clears it, so it will still remain after the connection is lost), but you can take care of it that).

+8
source

Source: https://habr.com/ru/post/1337228/


All Articles