0

次のチュートリアル ( http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server )に従い、以下に示すコードを取得しました。このコードにより、無制限の数のクライアントがチャットに接続できます。私がやりたいのは、このクライアント数を制限して、同じチャットルームで 2 人以上のユーザーがチャットできないようにすることです。

そのためには、実際に 1 つのことを知っておく必要があります。それは、すべてのクライアントの一意の識別子を取得する方法です。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();
4

1 に答える 1

1

これを試してください: でconnectionMade、クライアントの数が既に 2 の場合は、新しい接続を閉じます。

if len(self.factory.clients) == 2:
  self.transport.loseConnection()
于 2013-10-26T16:21:57.707 に答える