簡體   English   中英

在Twisted上實現每隔x秒調用一次服務器的客戶端

[英]Implement Client which call to server every x secs on Twisted

我正在嘗試創建客戶端應用程序(使用雙絞線),它將向服務器發送一些數據(始終相同)。 我需要這個來檢查服務器上的操作狀態。 但是我不知道如何使用Twisted做到這一點。

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

host = 'localhost'
port = 8007

class InstProtocol(Protocol):
    def __init__(self):
        with open('install_qeue.json','r') as jsonfile:
            self.json_data = jsonfile.read()
        jsonfile.close()
        self.json_data_status = self.json_data.replace('"end": 1', '"end": 2')

    def connectionMade(self):
        self.transport.write(self.json_data)

    def dataReceived(self, data):
        stdout.write(data)

    def sendMsg(self):
        self.transport.write(self.json_data_status)

class InstFactory(ClientFactory):
    protocol = InstProtocol

    def __init__(self):
        self.lc = task.LoopingCall(self.protocol.sendMsg)
        self.lc.start(10)

    def startedConnecting(self, connector):
        print 'Started to connect.'

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

    def clientConnectionLost(self, connector, reason):
        print 'Lost connection.  Reason:', reason

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason

reactor.connectTCP(host, port, InstFactory())
reactor.run()

錯誤:

Unhandled error in Deferred:


Traceback (most recent call last):
  File ".\client.py", line 97, in <module>
    reactor.connectTCP(host, port, InstFactory())
  File ".\client.py", line 82, in __init__
    self.lc.start(10)
  File "C:\Python27\lib\site-packages\twisted\internet\task.py", line 168, in start
    self()
  File "C:\Python27\lib\site-packages\twisted\internet\task.py", line 213, in __call__
    d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
  File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 150, in maybeDeferred
    result = f(*args, **kw)
exceptions.TypeError: unbound method sendMsg() must be called with InstProtocol instance as first argument (got nothing
instead)
Started to connect.

我該如何解決,請指教。

好,

  1. 將反應堆放入工廠的初始化
  2. 在data接收的協議寫入方法中:self.factory.reactor.callLater(30,self.build_log,data)
  3. 回調函數是一種協議方法,您需要在其中指定:接收到的輸出消息+發送另一條消息。

在這種情況下,每次您收到來自服務器的消息時,您都會在30秒內做出反應並發送另一個消息。 每個聯系服務器都收到了您的請求-它將立即發送響應。 這就是如何處理time.sleep()和while()循環的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM