简体   繁体   English

发送命令到扭曲的服务器

[英]Send commands to twisted server

I have a simple twisted TCP server that I am using to send and receive data from another application. 我有一个简单的双绞线TCP服务器,用于从另一个应用程序发送和接收数据。 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 我还有另一个模块(由GUI界面操作),该模块定义要发送的消息,并且需要将该消息作为“ msg”传递给connectionMade

What is the best way to do this? 做这个的最好方式是什么?

Your 3rd party call will happen from within connectionMade and should not call it directly. 您的第3方呼叫将connectionMade内部进行,并且不应直接呼叫。 The connectionMade is a Twisted callback and it's there to signal that a client is on the other side. connectionMade是一个Twisted回调,它在那里表示客户端在另一侧。 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). 因此,您可以执行一系列采取self.transport (包含相关客户数据)的Deferred s / callbacks之类的操作。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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