0
這是我的代碼,我正在尋找答案,但沒有解決我的問題。 我是新來扭曲,仍然在學習。Python未處理錯誤追蹤(最近呼叫最後):
爲什麼我在Windows命令提示符下運行telnet localhost 72
後出現此錯誤?
這是我的代碼:
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class chatprotocol(LineReceiver):
def __init__(self, factory):
self.factory = factory
self.name = None
self.state = "REGiSTER"
def connectionMade(self):
self.sendLine("What's your Name?")
def connectionLost(self, reason):
if self.name in self.factory.users:
del self.factory.Users[self.name]
self.broadcastMessage("%s has left channel." % (self.name,))
def lineReceived(self, line):
if self.state == "REGISTER":
self.handle_REGISTER(line)
else:
self.handle_CHAT(line)
def handle_REGISTER(self, name):
if name in self.factory.users:
self.sendLine("Name taken , please choose another")
return
self.sendline("welcome ,%s!" % (name,))
self.broadcastMessage("%s has joined the channel." % (name,))
self.name = name
self.factory.users[name] = self
self.state = "CHAT"
def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
self.broadcastMessage(message)
def broadcastMessage(self, message):
for name, protocol in self.factory.users.iteritems():
if protocol != self:
protocol.sendLine(message)
class ChatFactory(Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return chatprotocol(self)
reactor.listenTCP(72, ChatFactory())
reactor.run()
錯誤消息:
Unhandled Error
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext
return func(*args,**kw)
File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 149, in _doReadOrWrite
why = getattr(selectable, method)()
--- <exception caught here> ---
File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 1066, in doRead
protocol = self.factory.buildProtocol(self._buildAddr(addr))
File "C:\Python27\lib\site-packages\twisted\internet\protocol.py", line 131, in buildProtocol
p = self.protocol()
exceptions.TypeError: 'NoneType' object is not callable
很難理解從一些東西,但乍一看沒有與此LineReceiver正在由chatprotocol子類的問題,我的感覺是,出問題時的初始化LineReceiver。 – Marco
嘗試在'connectionMade'中初始化協議變量,並且不要覆蓋'__init__'方法(離開它的父版本)。 –
擁有''__init__''的@ESYSCODER很好,不會引起問題 –