please help me.. what does the following line do?
read_sockets,write_sockets,error_sockets =
select.select(CONNECTION_LIST,[],[])
This is a little tricky.
First,read the docs at
http://docs.python.org/2/library/select.html.
There's a lot of complicated stuff there, but just concentrate on the
description of the select.select() call for now.
Imagine a process which has a lot of network connections open. A great
example would be something like a MUD (Multi User Dungeon). You've got
one server process(*) and a bunch of clients which have all made TCP
connections over individual sockets.
Each client will be sending commands asynchronously, and the server
needs to handle this. You need some way to figure out which of those
sockets have something that's been sent to you (which you need to
process) and which are just sitting idle. That's where select() comes
in. It gives you a way to say, "Here's a list of sockets. Sleep until
one of them has something available for me to read, and let me know
which one."
One bit of complication is that you can also check for sockets which are
ready to be written on, and sockets which have some sort of error
condition. That's why the call returns a 3-tuple. But, for now, let's
just concentrate on reading.
Here's a very simplistic server which uses select():
import socket
import select
sock = socket.socket()
sock.bind(('localhost', 23000))
sock.listen(10)
# Accept four connections.
connections = []
for i in range(4):
s, addr = sock.accept()
print "Got connection from %s" % str(addr)
connections.append(s)
while True:
readable, _, _ = select.select(connections, [], [])
print "ready for reading: %s" % readable
for s in readable:
data = s.recv(1024)
print "Read from %s: %s" % (s, data)
You can write a little client which connects to this (I've got one I
used for testing, but I'll leave it to you to write one yourself as an
exercise). Connect four clients, and have them send some input in
random order.
Actually, this server has a bug (which you'll discover as soon as you
close one of the four connection), but it should serve to illustrate the
basic concept.
(*) I'm not sure if real MUDs are programmed this way, but it's a
plausible architecture. For simplicity sake, I'm assuming a
single-threaded server.