将从不同工厂接收的数据发送到多个工厂

2024-09-28 03:17:25 发布

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

有一个similar question here,但没有明确的答案。你知道吗

我需要能够监听一个端口(9000),并发送到不同端口(77778889999)上的其他服务器。你知道吗

我写的代码确实有效,但我不确定它是否是最好的方法。继续使用self.factory.factoryObjectList看起来不是pythonic。我希望我可以把它赋给另一个值来清理代码。你知道吗

我的方法是不是太过分了?这能用更简单的方法吗?你知道吗

import sys
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientFactory, ServerFactory
from twisted.protocols.basic import LineReceiver
from twisted.python import log

class RX_Protocol(LineReceiver):

    def dataReceived(self, data):
        self.sendMessageToConnections(self.factory.factoryObjectList, data)
        self.transport.write('sent \'%s\' to %d servers\n' % (data.strip(), self.countConnections(self.factory.factoryObjectList)))

    def connectionMade(self):
        self.transport.write('hello telnet user! Let\'s send a message to all connections\n')

    def sendMessageToConnections(self, factoryObjectList, data):
        for factoryObject in factoryObjectList:  # iterate through list of factory objects, 1 for each server
            for connection in factoryObject.factory.connections:  # now iterate through the actual connections of each factory
                connection.transport.write(data)

    def countConnections(self, factoryObjectList):
        counter = 0
        for factoryObject in factoryObjectList:
            if factoryObject.state == 'connected':
                counter += 1
        return counter


class RX_Factory(ServerFactory):
    protocol = RX_Protocol

    def __init__(self, factoryObjectList):
        self.factoryObjectList = factoryObjectList


## TX Stuff ##
class TX_Protocol(Protocol):

    def connectionMade(self):
        self.factory.connections.append(self)

    def connectionLost(self, reason):
        self.factory.connections.remove(self)


class TX_Factory(ClientFactory):  # subclass your factory of choice (Factory, ClientFactory, ServerFactory)
    protocol = TX_Protocol

    def __init__(self):
        self.connections = []

# spawn these in new terminals using nc -l XXXX
servers = [('localhost', 7777),
           ('localhost', 8888),
           ('localhost', 9999)]
# servers = [('localhost', 7777)]  # easier than opening 3 terminals

factoryObjectList = []  # will hold the multiple factories we use to connect to servers

# give us better STDOUT twisted logging
log.startLogging(sys.stdout)

for host, port in servers:
    factoryObjectList.append(reactor.connectTCP(host, port, TX_Factory()))

reactor.listenTCP(9000, RX_Factory(factoryObjectList))  #RX_Factory now "knows" about connections to servers
reactor.run()

Tags: toinimportselffordatafactorydef
1条回答
网友
1楼 · 发布于 2024-09-28 03:17:25

你的方法在我看来很典型。你知道吗

看看SO:What is the correct way to access a protocols transport in Twisted?(它也链接到另一个SO:Persistent connection in Twisted)有一个关于较新的“端点”系统的注释,您可能更喜欢它的样式。你知道吗

相关问题 更多 >

    热门问题