Twisted中TCP服务器的问题

1 投票
1 回答
1513 浏览
提问于 2025-04-15 23:44

我正在尝试使用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]获取连接信息,并把消息推送到目标连接上。但是这并没有成功。消息只在同一个连接中显示。希望有人能给我一些方向。

谢谢!

1 个回答

3

每当建立一个TCP连接时,Twisted会创建一个独特的实例来处理这个连接。所以,你在中只会看到一个连接。通常,这正是你想要的。不过,工厂(Factories)可以扩展来实现你想要的连接跟踪功能。具体来说,你可以创建一个的子类,并重写buildProtocol()方法来跟踪的实例。Twisted中所有类之间的关系需要一点时间来学习和适应。特别是,这部分内容来自标准的Twisted文档,在接下来的时间里,它会是你最好的朋友;-)

撰写回答