简体   繁体   English

如何使用python将数据从服务器发送到客户端?

[英]how send data from server to client using python twisted?

im new to python and im looking a way to send data from server to client. 我是python的新手,我正在寻找一种从服务器向客户端发送数据的方法。 i have a server monitoring program running on server and wanted to send notification via python server to python client 我有一个服务器监控程序在服务器上运行,并希望通过python服务器发送通知给python客户端

this is the server code 这是服务器代码

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()

client code 客户代码

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()

so far i found that if client send a message, server replies to that message but is there way to only send server data when data is available to client without expecting clients response? 到目前为止,我发现如果客户端发送一条消息,服务器会回复该消息,但是当数据可供客户端使用而不期望客户端响应时,是否只能发送服务器数据?

This server doesn't send replies to client messages. 此服务器不会发送对客户端消息的回复。 It sends a message when the client connects. 它在客户端连接时发送消息。 If that's not what you want, then try calling transport.write in a different event handler. 如果那不是您想要的,那么尝试在不同的事件处理程序中调用transport.write

If that's confusing, try thinking about defining when you want the server to send data to the client. 如果这令人困惑,请尝试考虑定义何时希望服务器将数据发送到客户端。

Do you want it to send data every five minutes? 你想让它每五分钟发送一次数据吗?

Do you want it to send data when a child process of the server exits? 您希望它在服务器的子进程退出时发送数据吗?

Do you want it to send it when an administrator clicks a button on the server? 当管理员单击服务器上的按钮时,您是否希望它发送它?

After you figure out what event should trigger data being sent then all you need to do is put your transport.write call into the method or function that handles that event. 在确定哪个事件应该触发数据发送之后,您需要做的就是将transport.write调用放入处理该事件的方法或函数中。

您可以使用AMP执行此操作,AMP是Twisted中的协议。

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

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