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

时间:2014-05-07 18:35:34

标签: python twisted

有一个similar question here,但没有明确的答案。

我需要能够侦听一个端口(9000),然后发送到不同端口的其他服务器(7777,8888,9999)。

我写的的代码有效,但我不确定它是不是最好的方法。持续使用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()

1 个答案:

答案 0 :(得分:1)

你的方法看起来很典型。

看看SO:What is the correct way to access a protocols transport in Twisted?(也链接到另一个SO:Persistent connection in Twisted)有一个关于较新的"端点"系统,你可能会更喜欢它的风格。