繁体   English   中英

使用基于Twisted的套接字限制聊天室中的用户数量

[英]Limit number of users in a chatroom with a Twisted-based socket

我遵循了以下教程( http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server ),并且得到了可以在下面看到的代码。 此代码允许无限数量的客户端连接到聊天。 我要做的是限制此客户端的数量,以使在同一聊天室中最多可以聊天两个用户。

为此,我实际上只需要知道一件事:如何为每个客户端获取唯一的标识符。 以后可以for c in self.factory.clients: c.message(msg)函数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();

尝试以下操作:在connectionMade ,如果客户端数量已经为2,则关闭新连接:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM