一个对等对象处理多个客户端

2024-10-04 01:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用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)

Tags: selfclienttrue客户端客户机ifdefexception
1条回答
网友
1楼 · 发布于 2024-10-04 01:31:42

to serve (send messages) future upcoming clients as well

这个句子很难理解。我的解释是,您希望sendUpdate将消息发送到除第一个客户机以外的所有客户机(按连接时的顺序)

but it only serves the first client

这同样困难。我的解释是,您观察到这样一种行为:只有第一个客户机(在连接时按排序)接收来自服务器的任何消息

以下是向客户端发送消息的代码:

connectedList[0].write('<update ' + str(updateCounter) + '>')

注意,这段代码总是向connectedList[0]发送一条消息。也就是说,它只向一个客户机发送消息-不管有多少个客户机-并且它总是选择connectedList中的第一个客户机(对应于连接到服务器的第一个客户机)

你可能想要更像这样的东西:

for c in connectedList[1:]:
    c.write('<update ' + str(updateCounter) + '>')

注意这是如何向多个客户机发送消息的

另外,与您的问题无关,您应该避免使用globals,并且应该避免使用裸的ITransport作为协议接口

相关问题 更多 >