是否会支持在多个端口上侦听,同时具有不同的“处理程序”(每个端口的不同回调集)?本质上,我希望我的进程在一个进程中托管两个服务器,每个进程执行不同的功能。我需要使用两个反应器才能做到这一点吗?
答案 0 :(得分:3)
是的,例如,修改quote server example您可以添加第二个实例,使用不同的引用在另一个端口上进行侦听:
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