Twisted - listening on multiple ports for multiple processes with one reactor

I need to run multiple instances of my server application, each in its own port. This is not a problem if I start them with os.system or subprocess.Popen, but I would like to have some process connection with multiprocessing.

I would like to somehow dynamically configure listening on different ports from different processes. Just calling the .listenTCP reactor does not do this because I get weird Errno 22 by stopping the reactor. I am also sure that this is not the right way to do this. I was looking for examples, but could not find anything. Any help is appreciated.

EDIT: Thanks Tzury, this is what I would like to receive. But I need to dynamically add ports for listening. For example

from twisted.internet import reactor 
from multiprocessing import Process 

def addListener(self, port, site): 
    ''' Called when I have to add new port to listen to. 
    site - factory handling input, NevowSite in my case''' 
    p = Process(target=f, args=(port, func)) 
    p.start() 

def f(self, port, func): 
    ''' Runs as a new process''' 
    reactor.listenTCP(port, func)

. react.stop() .

, ,

    --- <exception caught here> ---
  File "/usr/share/exe/twisted/internet/tcp.py", line 755, in doRead
    skt, addr = self.socket.accept()
  File "/usr/lib/python2.6/socket.py", line 195, in accept
    sock, addr = self._sock.accept()
<class 'socket.error'>: [Errno 22] Invalid argument

.

+3
1

, . () , , .

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
        self.transport.write("An apple a day keeps the doctor away\r\n") 
        self.transport.loseConnection()

# Next lines are magic:
factory = Factory()
factory.protocol = QOTD

# 8007 is the port you want to run under. Choose something >1024
reactor.listenTCP(8007, factory)
reactor.listenTCP(8008, factory)
reactor.run()
+9

Source: https://habr.com/ru/post/1717441/


All Articles