简体   繁体   中英

Send commands to twisted server

I have a simple twisted TCP server that I am using to send and receive data from another application. I am able to communicate and send messages to this application once a connection has been established.

What I want to be able to do have an external module command when and what to send to the 3rd party application (instead of when connected). For example, here is my server code:

from twisted.internet import reactor, protocol

# Twisted
class Tcp(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)
        print 'data received: ', data
        # do something with data


    def connectionMade(self, msg):
        # Want to only transport message when I command not immediately when connected
        self.transport.write(msg)


class TcpFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Tcp()

reactor.listenTCP(8001, TcpFactory())
reactor.run()

I have another module (operated by a GUI interface) which defines what message to send and this message needs to be passed as 'msg' into connectionMade

What is the best way to do this?

Your 3rd party call will happen from within connectionMade and should not call it directly. The connectionMade is a Twisted callback and it's there to signal that a client is on the other side. It's up to you to dictate what happens after that. So you can do something like make a series of Deferred s/callbacks which take self.transport (this holds relevant client data). In those series of callbacks, you'll have your logic for

  1. communicating with the 3rd party
  2. validating client
  3. sending a message to the client

This is the gist of it:

def connectionMade(self):
    d = Deferred()
    d.addCallback(self.thirdPartyComm).addErrBack(self.handleError)
    d.addCallback(sendMsg)
    d.callback(self.transport)

def thirdPartyComm(self, transport):
    # logic for talking to 3rd party goes here
    # 3rd party should validate the client then provide a msg
    # or raise exception if client is invalid
    return msg

def handleError(self, error):
    # something went wrong, kill client connection
    self.transport.loseConnection()

def sendMsg(self, msg):
    self.transport.write(msg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM