本文介绍了扭曲了多个端口,协议和反应器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扭曲的支持是否会同时在多个端口上监听不同的处理程序"(每个端口的回调集不同)?本质上,我希望我的进程在一个进程中托管两个服务器,每个服务器执行不同的功能.我需要使用两个反应堆吗?

Will twisted support listening on multiple ports, with different 'handlers' (different set of callbacks for each port) at the same time? Essentially, I want my process to host two servers in one process, each performing a different function. Would I need to use two reactors to do this?

推荐答案

是的,例如,修改引用服务器示例,您可以添加第二个实例,该实例在另一个端口上监听不同的报价:

Yes, for instance, modifying the quote server example you could add a second instance listening on a different port with a different quote:

from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
        # self.factory was set by the factory's default buildProtocol:
        self.transport.write(self.factory.quote + '\r\n')
        self.transport.loseConnection()


class QOTDFactory(Factory):

    # This will be used by the default buildProtocol to create new protocols:
    protocol = QOTD

    def __init__(self, quote=None):
        self.quote = quote or 'An apple a day keeps the doctor away'

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))

endpoint2 = TCP4ServerEndpoint(reactor, 8008)
endpoint2.listen(QOTDFactory("another configurable quote"))

reactor.run()

输出:

$ nc localhost 8007
configurable quote
$ nc localhost 8008
another configurable quote

这篇关于扭曲了多个端口,协议和反应器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 17:41