Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted - listen to multiple ports for multiple processes with one reactor

i need to run multiple instances of my server app each on it's own port. It's not a problem if i start these with os.system or subprocess.Popen, but i'd like to have some process communication with multiprocessing.

I'd like to somehow dynamically set up listening to different port from different processes. Just calling reactor.listenTCP doesn't do it, because i getting strange Errno 22 while stopping reactor. I'm also pretty sure it's not the correct way to do it. I looked for examples, but couldn't find anything. Any help is appreciated.

EDIT: Thanks Tzury, it's kinda what i'd like to get. But i have to dynamicly add ports to listen. 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)

I need a way to neatly stop such processes. Just calling reactor.stop() stop a child process doesn't do it.

This is the error i'm gettin when i trying to stop a process

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

Dimitri.

like image 615
user164039 Avatar asked Dec 17 '22 06:12

user164039


1 Answers

I am not sure what error you are getting. The following is an example from twisted site (modified) And as you can see, it listen on two ports, and can listen to many more.

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()
like image 66
Tzury Bar Yochay Avatar answered May 18 '23 14:05

Tzury Bar Yochay