我有一个使用TCP和Twisted的服务器客户机代码。我希望创建的第一个对等对象(按照第一个连接的客户机的顺序)也为(发送消息)将来的客户机服务。因此,我保存第一个对等方(全局列表)并将其用于所有即将进行的连接,但它只服务于它连接到的第一个客户机(),而忽略其他客户机
如何使对等机同时为所有连接的客户端提供服务?(我将对不超过3个客户端进行测试)
def connectionMade(self):
global connectedList
if self.pt == 'client':
self.connected = True
else:
print "Connected from", self.transport.client
try:
self.transport.write('<connection up>')
except Exception, e:
print e.args[0]
self.ts = time.time()
reactor.callLater(5, self.sendUpdate)
connectedList.append(self.transport) # add peer object
def sendUpdate(self):
global updateCounter, connectedList
print "Sending update"
try:
updateCounter += 1
print(connectedList[0])
# Send updates through first connected peer
connectedList[0].write('<update ' + str(updateCounter) + '>')
except Exception, ex1:
print "Exception trying to send: ", ex1.args[0]
if self.connected == True:
reactor.callLater(5, self.sendUpdate)
这个句子很难理解。我的解释是,您希望
sendUpdate
将消息发送到除第一个客户机以外的所有客户机(按连接时的顺序)这同样困难。我的解释是,您观察到这样一种行为:只有第一个客户机(在连接时按排序)接收来自服务器的任何消息
以下是向客户端发送消息的代码:
注意,这段代码总是向
connectedList[0]
发送一条消息。也就是说,它只向一个客户机发送消息-不管有多少个客户机-并且它总是选择connectedList
中的第一个客户机(对应于连接到服务器的第一个客户机)你可能想要更像这样的东西:
注意这是如何向多个客户机发送消息的
另外,与您的问题无关,您应该避免使用globals,并且应该避免使用裸的
ITransport
作为协议接口相关问题 更多 >
编程相关推荐