当我使用 twisted 创建TCP服务器时遇到TypeError
。
当我在启动 server.py 后运行 client.py 时,我会在错误追溯部分收到以下错误。
我不知道这个错误。但是,我确信错误发生在server.py
。
server.py:
from twisted.internet import protocol, reactor
from time import ctime
PORT = 1234
class TserverProtocols(protocol.Protocol):
def connectionMade(self):
clnt = self.clnt = self.transport.getPeer().host
print('...connected from:', clnt)
def dataReceived(self, data):
self.transport.write(('[%s] %s' %(ctime(),data)).encode())
factory = protocol.Factory()
factory.protocols = TserverProtocols
print('waiting for connetion...')
reactor.listenTCP(PORT, factory)
reactor.run()
client.py:
from twisted.internet import protocol, reactor
HOST = 'localhost'
PORT = 1234
class TSClntProtocol(protocol.Protocol):
def sendData(self):
data = input('>')
if data:
print('...sending %s' % data)
self.transport.write(data.encode())
else:
self.transport.loseConnetion()
def connectionMade(self):
self.sendData()
def dataReceived(self, data):
print(data)
self.sendData()
class TSCFactorty(protocol.ClientFactory):
protocol = TSClntProtocol
clientConnetionLost = clientConnectionFailed = lambda slef, connector, reason:reactor.stop()
reactor.connectTCP(HOST, PORT, TSCFactorty())
reactor.run()
错误追溯:
Unhandled Error
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/twisted/python/log.py", line 86, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/local/lib/python3.5/dist-packages/twisted/python/context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/local/lib/python3.5/dist-packages/twisted/python/context.py", line 85, in callWithContext
return func(*args,**kw)
File "/usr/local/lib/python3.5/dist-packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
why = selectable.doRead()
--- <exception caught here> ---
File "/usr/local/lib/python3.5/dist-packages/twisted/internet/tcp.py", line 1069, in doRead
protocol = self.factory.buildProtocol(self._buildAddr(addr))
File "/usr/local/lib/python3.5/dist-packages/twisted/internet/protocol.py", line 133, in buildProtocol
p = self.protocol()
builtins.TypeError: 'NoneType' object is not callable
答案 0 :(得分:0)
您的代码中有几个拼写错误。关于你的问题,你应该在server.py
中替换factory.protocols = TserverProtocols
与
factory.protocol = TserverProtocols