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