【问题标题】:how send data from server to client using python twisted?如何使用 python twisted 从服务器向客户端发送数据?
【发布时间】:2013-05-01 14:51:37
【问题描述】:

我是 python 新手,我正在寻找一种将数据从服务器发送到客户端的方法。我有一个在服务器上运行的服务器监控程序,想通过 python 服务器向 python 客户端发送通知

这是服务器代码

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
import time

class Server(Protocol):

    def connectionMade(self):
        self.transport.write("data to client")

factory = Factory()
factory.protocol = Server
reactor.listenTCP(8789, factory)
reactor.run()

客户端代码

from twisted.internet.protocol import Protocol, ClientFactory
from sys import stdout
from twisted.internet import reactor

class printData(Protocol):
    def dataReceived(self, data):
        stdout.write(data)

class ClientFactory(ClientFactory):
    def startedConnecting(self, connector):
        print 'connecting'

    def buildProtocol(self, addr):
        print 'Connected.'
        return printData()

    def clientConnectionLost(self, connector, reason):
        print reason

    def clientConnectionFailed(self, connector, reason):
        print reason

if __name__ == '__main__':
    reactor.connectTCP('localhost', 8789, ClientFactory())
    reactor.run()

到目前为止,我发现如果客户端发送消息,服务器会回复该消息,但是有没有办法只在客户端可以使用数据时才发送服务器数据而不期望客户端响应?

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    您可以使用 AMP(Twisted 中的一种协议)来执行此操作。

    【讨论】:

      【解决方案2】:

      此服务器不向客户端消息发送回复。当客户端连接时,它会发送一条消息。如果这不是您想要的,请尝试在不同的事件处理程序中调用 transport.write

      如果这令人困惑,请尝试考虑定义您希望服务器何时向客户端发送数据。

      您希望它每五分钟发送一次数据吗?

      你希望它在服务器的子进程退出时发送数据吗?

      您希望它在管理员单击服务器上的按钮时发送吗?

      在您确定应该触发数据发送的事件之后,您需要做的就是将您的 transport.write 调用放入处理该事件的方法或函数中。

      【讨论】:

      • 哦,对了,谢谢你的解释让我走上了正轨
      猜你喜欢
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 2017-09-23
      • 2015-02-10
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      相关资源
      最近更新 更多