2

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?

  • One reactor. Always only one reactor per process. But it can listen on multiple ports, serve multiple protocols, run a WebSocket Server on the same port where the HTTP content is served and so on. The reactor is the dispatcher for all the incoming events https://en.wikipedia.org/wiki/Reactor_pattern – Daniel F Jan 23 '19 at 10:25

1 Answers1

3

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
Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
  • Awesome answer. What about if I wanted to throw in something else, like a twisted WebSocket for example. Could I do that alongside those? – Ken - Enough about Monica Oct 29 '14 at 01:43
  • 1
    @horsehair I haven't tried it, but it should work fine. The reactor basically polls each socket and sends the data to the respective protocol when it arrives. Are you using http://autobahn.ws/ ? – Peter Gibson Oct 29 '14 at 01:47
  • I am trying to determine whether I should use autobahn.ws, but I was starting to think that Twister had built-in functionality that made using autobahn in addition to it redundant. For a simple WebSocket that just passes messages, at least. No? – Ken - Enough about Monica Oct 29 '14 at 02:02
  • 1
    @horsehair I'm not up to date with the development, but last time I checked the WebSocket branch was still under development – Peter Gibson Oct 29 '14 at 02:34
  • @PeterGibson, How can I run the demo in daemon mode with twistd ? – Allan K Liu Sep 14 '16 at 09:05