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();
但是通過這樣做,就不會有不止一個聊天室。因此,如果有4個用戶正在使用聊天功能,使用此代碼,他們將無法進行兩個並行對話,我錯了嗎? –