【问题标题】:How can I create a running list of connected protocols that have searchable attributes with twisted?如何创建具有可搜索属性的已连接协议的运行列表?
【发布时间】:2015-12-16 02:41:29
【问题描述】:

我正在尝试创建一个接受 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 还很陌生,对扭曲和网络是全新的,任何帮助或正确方向的点都会有所帮助! (作为旁注,我已经进行了相当广泛的搜索并找到了一些答案,但似乎没有任何答案。)

【问题讨论】:

    标签: python tcp server twisted


    【解决方案1】:

    我自己找到了答案,我想把它贴在这里。

    为了为我的每个协议实例创建一个唯一的名称,我在 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,这可用于在特定工厂范围内的任何位置引用连接。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 2023-04-06
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多