2

我正在尝试从其文档中学习扭曲的库。我创建了一个简单的聊天服务器,允许用户公开聊天。但是,我想知道是否可以为此添加私人聊天功能。我正在寻找你的想法。谢谢。

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    def __init__(self,users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self,line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:
            self.handle_CHAT(line)

    def handle_GETNAME(self,name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name))
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self,msg):
        msg = "<%s> %s" % (self.name,msg)
        for name,protocol in self.users.iteritems():
            if protocol != self:
                protocol.sendLine(msg)

class ChatFactory(Factory):
    def __init__(self):
        self.users = {}
    def buildProtocol(self, addr):
        return Chat(self.users)

reactor.listenTCP(8123,ChatFactory())  #@UndefinedVariable
reactor.run() #@UndefinedVariable
4

1 回答 1

1

实际上,我是通过更改 handle_CHAT 中的 for 循环来解决的。由于我希望程序将消息发送给特定用户,因此可以将“talkwith”字符串添加到类中,并且该字符串可以保存该特定用户的名称。然后这种变化将程序从公共聊天变成了私人聊天。

msg = "<%s> %s" % (self.name,msg)
            for name,protocol in self.users.iteritems():
                if name == self.talkwith:
                    protocol.sendLine(msg)
于 2013-08-06T14:51:24.720 回答