繁体   English   中英

Twisted聊天服务器中的broadcastMessage

[英]broadcastMessage in Twisted chat server

我在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!

PS:我正在使用Telnet发送消息。

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

在会话记录中,您输入名称“ Roman”并收到响应“ Welcome,Roman!”。 这是由于以下行:

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

与同一服务器的不同连接会收到消息“罗马已加入频道”。 由于行:

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

同样, broadcastMessage调用无法将“已加入”消息发送给加入的用户,因为在其调用时,“已加入”用户尚未添加到工厂的users字典中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM