John Doe
John Doe

Reputation: 10203

Listening on multiple ports

I'm playing a bit with Twisted and created a simple 'server'.
I'd like to let the server listening on multiple ports (1025-65535) instead of a single port.
How can i do this ?

My code:

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

class QuickDisconnectProtocol(Protocol): 
    def connectionMade(self): 
        print "Connection from : ", self.transport.getPeer()
        self.transport.loseConnection() # terminate connection


f = ServerFactory()
f.protocol = QuickDisconnectProtocol
reactor.listenTCP(6666,f)
reactor.run()

Already tried this:

for i in range (0, 64510):
    reactor.listenTCP(1025+i,f)

reactor.run()

But received an error:

Traceback (most recent call last):
  File "Server.py", line 14, in <module>
  File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 436, in listenTCP
  File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 641, in startListening
twisted.internet.error.CannotListenError: Couldn't listen on any:2044: [Errno 24] Too many open files.

Upvotes: 1

Views: 1738

Answers (2)

Glyph
Glyph

Reputation: 31860

Each listening port requires a file descriptor ("open file"), and each file descriptor takes up one element of your maximum file descriptors quota.

This stack overflow question has an answer explaining how to raise this limit on Linux, and this blog post has resources as to how to do it on OS X.

That said, the other respondents who have told you that this is not a particularly sane thing to do are right. In particular, your operating system may stop working if you actually go all the way up to 65535, this overrules the entire ephemeral port range, which means you may not be able to make TCP client connections from this machine any more. So it would be good to explain in your question why you are trying to do this.

Upvotes: 3

ravenspoint
ravenspoint

Reputation: 20472

The usual solution is to have one listening port ( chosen by the server! ). If you want each client on its own port, then the server chooses the port, starts listening on it, and replies to the client with the port it will use for further requests.

It is not a real good use of port resources! If the server needs to keep state information for each client then it should issue a unique ID to each client when the client first connects and the client should use this ID for every request to the server.

However, with a little care, you can often design the system so that the server does not need to keep separate state information for each client.

Upvotes: 2

Related Questions