Twisted聊天服务器中的broadcastMessage

时间:2017-08-22 14:31:41

标签: python python-2.7 chat twisted

我在Twisted中编写聊天服务器,我在理解 broacastMessage()方法时遇到了问题:

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>)。现在,当迭代这个元组namesprotocols时,我们正在比较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 发送消息。

1 个答案:

答案 0 :(得分:0)

你确定它不起作用吗?根据您的终端会话记录和本地测试,它看起来对我有用。

在您的会话记录中,您输入了名称&#34; Roman&#34;并收到了回复#34;欢迎,罗马!&#34;。这是由于行:

self.sendLine("Welcome, %s!" % (name,))

与同一服务器的不同连接收到消息&#34; Roman已加入该频道。&#34;由于这条线:

self.broadcastMessage("%s has joined the channel." % (name,))

此外,broadcastMessage来电无法发送&#34;加入&#34;消息给加入的用户,因为在通话时,&#34;加入&#34;用户尚未添加到工厂的users字典中。