gpt4 book ai didi

python - Twisted 中的 TCP 服务器问题

转载 作者:可可西里 更新时间:2023-11-01 02:47:47 27 4
gpt4 key购买 nike

我正在尝试使用 Twisted 制作一个简单的 TCP 服务器,它可以在不同的客户端连接之间进行一些交互。主要代码如下:

#!/usr/bin/env python
from twisted.internet import protocol, reactor
from time import ctime

#global variables
PORT = 22334
connlist = {} #store all the connections
ids = {} #map the from-to relationships

class TSServerProtocol(protocol.Protocol):

def dataReceived(self, data):
from_id,to_id = data.split('|') #get the IDs from standard client input,which looks like "from_id|to_id"

if self.haveConn(from_id): #try to store new connections' informations
pass
else:
self.setConn(from_id)
self.setIds(from_id,to_id)

if to_id in self.csids.keys():
self.connlist[to_id].transport.write(\
"you get a message now!from %s \n" % from_id) #if the to_id target found,push him a message.doesn't work as expected
def setConn(self,sid):
connlist[sid] = self

#some other functions

factory = protocol.Factory()
factory.protocol = TSServerProtocol
print 'waiting from connetction...'
reactor.listenTCP(PORT, factory)
reactor.run()

如评论所述,如果有新的客户端连接,我会将其连接句柄存储在全局变量 connlist 中,类似于

connlist = {a_from_id:a_conObj,b_from_id:b_conObj,....}

并解析输入,然后将其从到信息映射到 ids 中。然后我检查 ids 中是否有与当前“to_id”匹配的键。如果是,使用 connlist[to_id] 获取连接句柄并将消息推送到目标连接。但它不起作用。消息仅在同一连接中显示。希望有人能告诉我一些关于这个。

谢谢!

最佳答案

每次建立 TCP 连接时,Twisted 都会创建一个唯一的 TSServerProtocol 实例来处理该连接。因此,您只会在 TSServerProtocol 中看到 1 个连接。通常,这就是您想要的,但可以扩展 Factories 来执行您在此处尝试执行的连接跟踪。具体来说,您可以子类化 Factory 并覆盖 buildProtocol() 方法以跟踪 TSServerProtocol 的实例。 Twisted 中所有类之间的相互关系需要一点时间来学习和习惯。特别是这 block standard Twisted documentation应该是你接下来最好的 friend ;-)

关于python - Twisted 中的 TCP 服务器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com