Twisted Python 在 TCP/IP 连接中的应用?

Application of Twisted Python in TCP/IP connections?

我正在写一个客户端,需要建立几个独立的通信通道,每个通道在服务器上都有自己唯一的端口,通过一系列的发送和接收消息与服务器进行通信。我知道如何使用套接字发送和接收来完成此操作,方法是为每个通信通道提供一个套接字,然后在该套接字上执行发送和接收。我需要在 Twisted 中完成这项工作,并找到了可能有用的接口,包括 Factory 和 ProcessProtocol。但是,协议接口不提供发送消息的方法。 ProcessProtocol 是否适合我的任务,以及我如何让 ProcessProtocol 发送消息?

如果你不知道,我想对优秀的 Twisted finger tutorial 大声疾呼,它以良好的速度通过图书馆,但有足够的细节让你知道发生了什么在。

不过,为了直接回答您的问题,我想说您在 Protocol 和 (Client)Factory 方面走在了正确的轨道上。我认为最干净的方法来做你正在寻找的东西(假设你需要连接到不同的端口,因为它们是不同数据的输出)是为你想要连接的每个端口制作一个 factory/protocol 对 to/handle,然后使用外部 class 来处理聚合所有这些应用程序逻辑。通常您不希望您的应用程序逻辑与您的网络逻辑深度混合。

一个简单的例子:(注意使用self.transport.write发送数据)

from twisted.internet.protocol import Protocol, ClientFactory
from sys import stdout

from foobar_application import CustomAppObject

class FooProtocol(Protocol):
    def connectionMade(self):
        # Use self.transport.write to send data to the server
        self.transport.write('Hello server this is the Foo protocol.')
        self.factory.do_app_logic()

class FooFactory(ClientFactory):
    protocol = FooProtocol

    def __init__(self, app_object=None):
        self.app = app_object

    def do_app_logic(self):
        self.app.do_something()

class BarProtocol(Protocol):
    def dataReceived(self, data):
        stdout.write('Received data from server using the Bar protocol.')
        self.factory.do_fancy_logic(data)

class BarFactory(ClientFactory):
    protocol = BarProtocol

    def __init__(self, app_object=None):
        self.app = app_object

    def do_fancy_logic(self, data):
        self.app.do_something_else(data)

logic_obj = CustomAppObject()
reactor.listenTCP(8888, FooFactory(app_object=logic_obj)
reactor.listenTCP(9999, BarFactory(app_object=logic_obj)
reactor.run()

您可能还想查看 'Writing Clients' docs on the Twisted site