问题
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