#!/usr/bin/python

import select
import socket
import time

PORT=30005
MAX_CLIENTS=32
connections = list()


# Get / Accept connections on separate thread
svrSoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = PORT
svrSoc.bind(("", port))
svrSoc.listen(5)

#try:
if 1 == 1:
	while True:
		readFds = [ svrSoc ]
		writeFds = []	# writeFds = [ svrSoc ]
		exceptFds = [ svrSoc ]
		for fd in connections:
			readFds.append(fd)
			# writeFds.append(fd)
			exceptFds.append(fd)
		readList, writeList, exceptList = select.select(readFds, writeFds, exceptFds, 0)
		if len(readList) > 0 or len(writeList) > 0 or len(exceptList) > 0:
			if len(readList) > 0:
				print("Read FD needs attention")
				if svrSoc in readList:
					conn, addr = svrSoc.accept()
					print("Connection accepted from: %s:%s" % (addr[0], addr[1]))
					connections.append(conn)
					conn.setblocking(0)
					readList.remove(svrSoc)

				for fd in readList:
					data = fd.recv(8192)
					if not data:	# Assuming socket closed
						fd.close()
						connections.remove(fd)
						print("Removed connection: %d remain" % len(connections))
						
			if len(exceptList) > 0:
				print("Except FD needs attention")
				if svrSoc in exceptList:
					print("Listen Socket has exception")
			
		
		# Do hat stuff
		

#except:
#	print("Exception occurred")
	
