如何创建 运行 已连接协议的列表,这些协议具有可搜索的扭曲属性?

How can I create a running list of connected protocols that have searchable attributes with twisted?

我正在尝试创建一个服务器来接受具有 运行 当前连接列表的 TCP 连接。我目前的工厂和协议如下:

class KConnectProtocol(Protocol):
...

    # Adds +1 to the client count whenever a new connection is made, while     
    # also putting a log entry for the client IP and time stamp.
    def connectionMade(self):
        self.client = self.transport.client
        log.msg('K connected from: ' + self.client[0])
        self.factory.numProtocols = self.factory.numProtocols + 1
        log.msg('There are ' + str(self.factory.numProtocols) + ' k connected.')

        self.factory.kList.append(self)
...

class KFactory(ServerFactory):

     # numProtocols keeps track of the number of clients connected to the server at
     # any given point. It's an attribute of the factory so it can be called globally
     protocol = KConnectProtocol
     numProtocols = 0
     kList = []
     uid = []

现在,我希望能够做的是根据每个协议的 UID 搜索 kList。即;

k1.uid = 123
k2.uid = 234
k3.uid = 345

kList = (k1, k2, k3)

现在,列表中的每一项都代表一个唯一的 TCP 连接。我想在 kList 中搜索属性“234”。一旦确定了对象的索引,我 应该 能够执行 k2.transport.write("Whoopee") 通过该特定 TCP 连接发送内容。但是,我 运行 遇到了一个障碍,我不确定在哪里声明该属性,也不知道列表是否可以搜索到那个程度。

为了涵盖所有问题,我的问题如下:

  1. 我应该在哪里创建属性 (uid) 以便每个连接在协议初始化中都有一个唯一的标识符?
  2. 如何制作可根据该属性搜索的对象(协议)列表?

我是 python 的新手,也是 twisted 和网络的新手,任何帮助或正确方向的观点都会有所帮助! (作为旁注,我进行了非常广泛的搜索并找到了一些答案,但似乎没有任何答案。)

我已经为自己找到了答案,我想 post 在这里。

为了为我的每个协议实例创建一个唯一的名称,我在 connectionMade 方法中创建了属性:

class KConnectProtocol(Protocol):

    # Adds +1 to the client count whenever a new connection is made, while
    # also putting a log entry for the client IP and time stamp.
    def connectionMade(self):
        self.client = self.transport.client
        log.msg('K connected from: ' + self.client[0])
        self.factory.numProtocols = self.factory.numProtocols + 1
        log.msg('There are ' + str(self.factory.numProtocols) + ' k connected.')

        self.factory.kList.append(self)

        self.kUID = ""

这会将其作为属性添加到所创建的每个实例(连接)中,因此您可以为每个实例设置自己的标识符。

    for x in self.factory.kList:
        if x.kUID == "12345":
            x.transport.write("It works!\n")

在这里,我能够识别特定的连接,并使用该 UID 将信息发送到该连接。

执行 print x.__dict__ 实际上会打印该实例的所有内容,这正是我找到答案的原因。通过工厂跟踪 kList,这可用于在特定工厂范围内的任何位置引用连接。

我仍在努力提高效率,但希望这对其他人也有帮助!