views:

223

answers:

4

I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if they are not in the same program? I do not quite understand how to make this useful.

+1  A: 

You need to retrieve the port that was assigned to the socketserver once the bind is done: in this case, this will probably be through ip, port = server.server_address.

The arbitrary port is just if you want to create a server without specifying a port: the OS will assign an available port.

Of course there must also be a way to specify which port to bind to.

jldupont
+2  A: 

In the example you linked, they are fetching the port:

# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0

server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address

However, you should really be looking at www.twistedmatrix.com if you are serious about writing async handling :)

truppo
+1. Twisted is the way to go.
Jason Orendorff
+4  A: 

Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server.

AJ
A: 
server = ThreadedTCPServer((HOST, 0), ThreadedTCPRequestHandler)
ip, port = server.server_address

...

client(ip, port, "Hello World 1")

The PORT value 0 says "I don't care what port number it is," so the server_address's port value is assigned by the ThreadedTCPServer() call. It is not zero. Later, you pass that port value to the client, who uses it.

Ewan Todd