26
Feb
09

simplest way to use select with sockets?



I’ve been playing recently with python and network programming. IMHO, writing a server that makes use of select seems to be the simplest select code I’ve ever read/wrote. Here’s how it goes:



import socket,select,sys,pdb

if(len(sys.argv) != 2):
	print "a port must be supplied"
	exit(1)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
read_list = [sock]
sock.bind(("localhost",int(sys.argv[1])))
sock.listen(5)

while 1:
	current_data = ""	
	infds,outfds,errfds = select.select(read_list,[],read_list,0.05)
	if len(infds):
		for socket in infds:
			if socket==sock:
				clientsock,client_addr = sock.accept()
				read_list.append(clientsock)
			else:
				current_data = socket.recv(4196)
				if(not len(current_data)):
					print "client disconnected"
					read_list.remove(socket)
		for socket in [socket for socket in read_list if socket != sock]:
			if current_data != "":
				socket.send("a client wrote:%s"%current_data)

The code illustrates a VERY basic messaging “application”, that will listen on a user-supplied port. Each time a client writes a message, the server sends the message to all connected sockets. The message doesn’t get sent to server again ( notice the socket != sock ). The deal with select is that you need to supply it with a list to check for available data, this is the read_list. I’m no socket guru, but this really looks simple, right?

Advertisements

0 Responses to “simplest way to use select with sockets?”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Blog Stats

  • 229,301 hits

%d bloggers like this: