简体   繁体   中英

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. i have a server monitoring program running on server and wanted to send notification via python server to python client

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.

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.

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

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