[Twisted-Python] Sending disconnect messages to clients

Chris Norman chris.norman2 at googlemail.com
Tue Mar 22 13:42:06 MDT 2016


Hi all,
I'm sure I asked this question before, but I can't find any answers on 
google, and I've changed my work flow a bit now, so thought it was worth 
re-asking.

So on my server's protocol, I have a send method. This allows me to pass 
arguments which get sent off to the client in the right format. The send 
method looks something like this:

  def send(self, command, **kwargs):
   """Cause the client to issue getattr(connection, command)(**kwargs). 
If disconnect evaluates to True, disconnect the client after the message 
is sent."""
   disconnect = kwargs.get('disconnect', False)
   try:
    del kwargs['disconnect']
   except KeyError:
    pass # Argument not found.
   d = defer.Deferred()
   d.addCallback(self.prepare_command) Convert the command and kwargs to 
json.
   d.addCallback(self.deferred_write) # Write the json to the transport.
   if disconnect:
    d.addCallback(self.deferred_disconnect) # Issue 
self.transport.loseConnection().
   reactor.callFromThread(d.callback, [command, kwargs]) # Call the 
deferred's callback chain.
   return d # Return the deferred.

If I try something like:
protocol.send('alert', message = '*** Disconnected. ***', disconnect = True)
the client gets disconnected, but never sees the "*** Disconnected. ***" 
message.

I guess I could do a reactor.callLater and just wait for the transport 
to get the message, but that seems sloppy, and I can't help thinking 
there must be something I'm missing.

Any ideas welcome!

Cheers all,




More information about the Twisted-Python mailing list