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