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