我正在尝试创建客户端应用程序(使用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.
我该如何解决,请提出建议。
答案 0 :(得分:0)
那么,
在这种情况下,每次从服务器收到消息时 - 您将在30秒内做出反应并发送另一个消息。每个领带服务器都有你的请求 - 它会立即发送响应。那是如何处理这个w \ o time.sleep()和while()循环。