Twisted with multiple ports, protocols, and reactors

与世无争的帅哥 提交于 2020-02-24 21:16:35

问题


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?


回答1:


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()

Output:

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


来源:https://stackoverflow.com/questions/26621431/twisted-with-multiple-ports-protocols-and-reactors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!