用多个端口、协议和反应器配置Twisted
请问twisted能否同时在多个端口上监听,并且为每个端口设置不同的处理函数(也就是每个端口有一套不同的回调函数)?简单来说,我想让我的程序在一个进程里同时运行两个服务器,每个服务器执行不同的功能。这样做的话,我需要使用两个反应器吗?
1 个回答
3
是的,比如说,你可以修改这个报价服务器的例子,让它在另一个端口上再开一个实例,并且这个实例可以返回不同的报价:
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