import socket
import sys
from thread import *
HOST=''#Symbolic name meaning all available interfaces
PORT=8888#Arbitrary non-privileged port
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print 'Socket created!'
try:
	s.bind((HOST,PORT))
except socket.error, msg:
	print 'Bind failed.Error code: '+str(msg[0])+' Error message:'+msg[1]
	sys.exit()
print 'Socket bind successfully!'
s.listen(10)
print 'Now socket listening!'
#Function for handling connections.This will be used to creat threads
def clientthread(conn):
	#sending message to connected client
	conn.send('Welcome to the server.Type something and hit enter\n')#send only takes string
	#infinite loop so that function do not terminate and thread do not end.
	while True:
			#Receiving from client
			data=conn.recv(1024)
			reply='\tOK! Server received: '+data+'\n'
			if not data:
				break
			if data=='q':
				break
			conn.sendall(reply)

	#came out of loop
	conn.close()
#now keep talking with client
while 1:
	#wait to accept a connection -blocking call
	conn,addr=s.accept()
	#display client information
	print 'Connected with '+addr[0]+':'+str(addr[1])
	#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
	start_new_thread(clientthread,(conn,))
conn.close()

s.close()