【发布时间】:2017-08-22 14:31:41
【问题描述】:
我正在 Twisted 中编写聊天服务器,但在理解 broadcastMessage() 方法时遇到问题:
def broadcastMessage(self, message):
print list(self.factory.users.iteritems())
for name, protocol in self.factory.users.iteritems():
if protocol != self:
protocol.sendLine(message)
我知道 iteritems() 应该产生一个元组,例如('Roman', <__main__.ChatProtocol instance at 0x7fc80b8b67a0>)。现在,当遍历这个元组 names 和 protocols 时,我们正在比较 protocol 如果它不是 self 实例,仅仅是因为我们不想为发送它的用户打印消息? (我说对了吗?)
所以期望它可以工作,但由于某种原因它没有。这是代码:
from twisted.internet import protocol, reactor
from twisted.protocols.basic import LineReceiver
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, 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(protocol.Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return ChatProtocol(self)
reactor.listenTCP(8000, ChatFactory())
reactor.run()
这是终端会话:
(venv) metal@space ~/Documents/learning/twisted/chat_server $ telnet localhost 8000
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
What's your name?
Roman
Welcome, Roman!
P.S.:我正在使用 Telnet 发送消息。
【问题讨论】:
标签: python python-2.7 chat twisted