Python Twisted中的多组聊天服务器

1 投票
1 回答
1907 浏览
提问于 2025-04-18 10:12

我正在使用Twisted框架搭建一个聊天服务器,现在这个服务器对一个群组运行得很好,但我需要支持多个群组。这样用户就可以加入特定的群组,并且可以向那个群组发送和接收消息。那么,怎么才能创建多个群组呢?我想要一个功能叫做'joinroom(self, roomname)',用户可以通过这个功能被引导到他们想加入的群组。

from twisted.internet import reactor,protocol                                           
from twisted.protocols import basic                                            
from twisted.internet.protocol import Protocol, ClientFactory                  
import time                                                                              

def t():

return "["+ time.strftime("%H:%M:%S") +"] "                                          

class EchoProtocol(basic.LineReceiver):                                                  
  name = "Unnamed"                                                                     

  def connectionMade(self):                                                            

    self.transport.write("WhiteNOISE"+"\n")                                          
    self.sendLine("Enter A name Below...")                                           
    self.sendLine("")                                                                
    self.count = 0                                                                   
    self.factory.clients.append(self)                                                
    self.factory.group.append(self)                                                  
    print t() + "+ Connection from: "+ self.transport.getPeer().host                 

  def connectionLost(self, reason):                                                    

    self.sendMsg("- %s left." % self.name)                                           
    print t() + "- Connection lost: "+ self.name                                     
    self.factory.clients.remove(self) 
  def dataReceived(self, data):                                                        
        #print "data is ", data                                                      
            a = data.split(':')                                                      
            if len(a) > 1:                                                           
                    command = a[0]                                                   
                    content = a[1]                                                   


                    msg = ""                                                         
                    if command == "iam":                                             
                            self.name = content                                      
                            msg = self.name + " has joined"                          

                    elif command == "msg":                                           
                            msg = self.name + ": " + content                         
                    elif command  == "quit":                                         
                            self.transport.loseConnection()                          
                            return                                                   
                    elif command == "/ul":                                           
                            self.chatters()                                          
                            return()                                                 

                    print msg
                    self.sendMsg(msg)

  def username(self, line):                                                            

    for x in self.factory.clients:                                         
        if x.name == line:                                                 
            self.sendLine("This username is taken; please choose another")           
            return                                                                   

    self.name = line                                                                 
    self.chatters()                                                                  
    self.sendLine("You have been connected!")                                        
    self.sendLine("")                                                                
    self.count += 1                                                                  
    self.sendMsg("+ %s joined." % self.name)                                         
    print '%s~ %s connected as: %s' % (t(), self.transport.getPeer().host, self.name)

  def chatters(self):                                                                  
    x = len(self.factory.clients) - 1                                                
    s = 'is' if x == 1 else 'are'                                                    
    p = 'person' if x == 1 else 'people'                                             
    self.sendLine("There %s %i other %s connected:" % (s, x, p) )                    

    for client in self.factory.clients:                                              
        if client is not self:                                                       
            self.sendLine(client.name)                                               
    self.sendLine("")

  def sendMsg(self, message):                                                          

    for client in self.factory.clients:                                              
        client.transport.write( message + '\n')                                      



class EchoServerFactory(protocol.ClientFactory):                                         
protocol  = EchoProtocol                                                             
clients = []                                                                         

if __name__ == "__main__":                                                               
reactor.listenTCP(5001, EchoServerFactory())                                         
print "Chat Server Started"                                                          
reactor.run()

1 个回答

1

这里有一些伪代码,我看到你在你的工厂里已经创建了一个叫做 group 的变量,所以我猜你有类似的想法,但可以试试用字典而不是列表,这样你可以更优雅地命名和访问你的组。

当然,这意味着你的 "msg" 命令需要指定组,这样你才能知道要把消息发送到哪个组。

class EchoServerFactory(protocol.ClientFactory):                                         
   protocol  = EchoProtocol                                                             
   clients = []
   groups = {}    

def dataReceived(self, data):                                                        
   # Split string ,error checking ...
   if command == "join":                                             
      self.factory.groups.get(content, []).append(self)  
   # handle other commands             

def sendMsg(self, message, group):                                                          
   for client in self.factory.groups[group]:                                              
      client.transport.write( message + '\n') 

不过这真的很简单,比如说没有滚动功能,所以新来的客户端看不到聊天记录,消息的发送也不可靠,因为你没有使用任何确认机制来告诉服务器客户端是否真的收到了消息,或者服务器是否需要把消息重新发送给某些客户端。

更好、更稳健的解决方案可能包括:

  • 使用 Twisted IRC 服务器协议
  • 使用 TwistedWords 即时消息服务器/客户端(简单)
  • 使用 Redis PubSub,可以轻松地将消息从单个客户端发送到所有在同一频道上订阅的其他客户端(不可靠,几乎可以轻松实现)
  • 使用 RabbitMQ 将消息路由到所需的客户端或其他消息代理(可靠、稳健,但比 Redis 或 TwistedWords 需要更多的设置)

这里简单解释一下我所说的可靠和不可靠的概念。

可靠消息传递是指在不可靠的基础设施上进行消息通信,同时能够对消息成功传输做出某些保证;例如,如果消息被送达,它最多只会送达一次,或者所有成功送达的消息会按照特定的顺序到达。

免责声明:我只是建议了一些我过去使用过的技术和想法,可能还有成百上千种其他方法来实现[简单、稳健]的群聊。

撰写回答