【问题标题】:Implement Client which call to server every x secs on Twisted在 Twisted 上实现每 x 秒调用一次服务器的客户端
【发布时间】:2015-08-06 21:30:27
【问题描述】:

我正在尝试创建客户端应用程序(使用扭曲),它将向服务器发送一些数据(始终相同)。我需要这个来检查服务器上的操作状态。 但我不知道如何使用 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.

如何解决,请指教。

【问题讨论】:

  • 其实我理解这个错误。我试图在类上调用非类方法(protocol = InstProtocol

标签: python sockets networking twisted


【解决方案1】:

嗯,

  1. 将反应器放入工厂的init
  2. 在协议写入的dataReceived方法中:self.factory.reactor.callLater(30, self.build_log, data)
  3. 回调函数是一种协议方法,需要指定:输出消息接收+发送另一条消息。

在这种情况下,每次您收到来自服务器的消息 - 您将在 30 秒内做出反应并发送另一条消息。每个领带服务器都会收到您的请求 - 它会立即发送响应。这就是处理这个没有 time.sleep() 和 while() 循环的方法。

【讨论】:

    猜你喜欢
    • 2013-12-24
    • 2013-07-30
    • 2017-07-23
    • 2019-01-09
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2019-10-25
    相关资源
    最近更新 更多