我遵循了以下教程(http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server),并且得到了可以在下面看到的代码。此代码允许无限数量的客户端连接到聊天。我想做的是限制此客户端的数量,以使在同一聊天室中最多可以有两个用户聊天。
为此,我实际上只需要知道一件事:如何为每个客户端获取唯一的标识符。以后可以在功能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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句