2013-10-26 33 views
0

我遵循以下教程(http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server),我得到了您可以在下面看到的代码。此代码允许无限数量的客户端连接到聊天。我想要做的就是限制这个客户端数量,以便不超过两个用户可以在同一个聊天室聊天。使用基于Twisted的套接字限制聊天室中的用户数

为了做到这一点,我只需要知道一件事:如何为每个客户端获得唯一的标识符。以后可以在函数for c in self.factory.clients: c.message(msg)中使用它,以便仅将消息发送到我想要的客户端。

我会感谢任何贡献!

# Import from Twisted 
from twisted.internet.protocol import Factory, Protocol 
from twisted.internet import reactor 

# IphoneChat: our own protocol 
class IphoneChat(Protocol): 

    def connectionMade(self): 
     self.factory.clients.append(self) 
     print "Clients are ", self.factory.clients 

    def connectionLost(self, reason): 
     self.factory.clients.remove(self) 

    def dataReceived(self, data): 
     a = data.split(':') 
     print a 

     if len(a) > 1: 
      command = a[0] 
      content = a[1] 

      msg = "" 
      if command == "iam": 
       self.name = content 

      elif command == "msg": 
       msg = self.name + ": " + content 

       for c in self.factory.clients: 
        c.message(msg) 

    def message(self, message): 
     self.transport.write(message + '\n') 


# Factory: handles all the socket connections 
factory = Factory() 
factory.clients = [] 
factory.protocol = IphoneChat 

# Reactor: listens to factory 
reactor.listenTCP(80, factory) 
print "Iphone Chat server started" 
reactor.run(); 

回答

1

试试这个:在connectionMade,如果客户数量已经是2,关闭新的连接:

if len(self.factory.clients) == 2: 
    self.transport.loseConnection() 
+0

但是通过这样做,就不会有不止一个聊天室。因此,如果有4个用户正在使用聊天功能,使用此代码,他们将无法进行两个并行对话,我错了吗? –