0

I followed the following tutorial (http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server) and I got the code you can see below. This code allows an unlimited number of clients to connect to a chat. What I want to do is to limit this number of clients so that no more than two users can chat at the same chatroom.

In order to do so, I actually just need to know one thing: how to get a unique identifier for every client. Which can be used later on, in the function for c in self.factory.clients: c.message(msg) in order to only send the message to the client I want.

I'd appreciate any contribution!

# 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 回答