我正在学习Python Twisted,这是我的书中关于聊天服务器的例子:
project.with {
plugins.withType(JavaPlugin) {
//noinspection GroovyAssignabilityCheck
configurations.all {
resolutionStrategy {
force localGroovy()
}
}
}
}
我连接:telnet localhost 7100。 它工作并问我:你的名字是什么?但是当我输入我的名字时,服务器会引发这个错误:
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 the 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, choose another!")
return
self.sendLine("Welcome, %s !" %(name))
self.broadcastMessage("%s has joined 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(7100, ChatFactory())
reactor.run()
我对此非常陌生,所以我真的不太懂。
答案 0 :(得分:0)
Python区分大小写。
你有:
def LineReceived(self, line):
...
但你应该有:
def lineReceived(self, line):
...
由于您定义的方法没有正确的名称,因此使用继承的方法。该方法的实现可以引发您所看到的异常。
此外,切换到使用四个空格缩进。它将提高可读性,它本质上是Python的标准。