【发布时间】: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