实现在Twisted上每隔x秒调用服务器的客户端

时间:2015-08-06 21:30:28

标签: python sockets networking twisted

我正在尝试创建客户端应用程序(使用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 个答案:

答案 0 :(得分:0)

那么,

  1. 将reactor放入Factory
  2. init 协议写入的dataReceived方法中的
  3. :self.factory.reactor.callLater(30,self.build_log,data)
  4. 回调函数是一种协议方法,您需要指定:收到的输出消息+发送另一条消息。
  5. 在这种情况下,每次从服务器收到消息时 - 您将在30秒内做出反应并发送另一个消息。每个领带服务器都有你的请求 - 它会立即发送响应。那是如何处理这个w \ o time.sleep()和while()循环。