#!/usr/bin/env python # Basic Echo Server - socketserver.py import socket, traceback, sys host = '' # Binds to all, anyone can connect port = 50000 # Create socket s( IPv4 , TCP ) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Setting Socket Options( level , optname , value) # SO_REUSEADDR: Releases port immediately after server stops s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) # Binds the server to a host add a port number s.listen(5) # Tells the server to listen for connections # 5 is the amount of queues the server will allow once = 0 # Bool if a connection has already been made while(5): if once: print "\n Awaiting more connections...", print "If you are tired and wish to stop, press Ctrl-C!" else: print "\n Awaiting connections...", print "If you are tired and wish to stop, press Ctrl-C!" try: clientsock, clientaddr = s.accept() except KeyboardInterrupt: # Allows user to cancel with Ctrl-C while opening connection raise except: # Prints out any other error, but does not kill the server traceback.print_exc() continue #Sets time before timeout is triggered clientsock.settimeout(100) # Process Connection try: name = clientsock.recv(4096) print "\n%s connected from" % name, clientsock.getpeername() onceChat = 0 # Sets to beginning chat message print " Awaiting message.... " while 1: if onceChat: print " Awaiting response...." # Waits until data is recieved, passes into variable data data = clientsock.recv(4096) if not len(data): break print "%s says: %s" % (name, data) print "Server says?: ", data = sys.stdin.readline().strip() # Sends message to the client clientsock.sendall(data) onceChat = 1 # Continuous chat style triggered except (KeyboardInterrupt, SystemExit): raise except socket.timeout: print "Client timed out. ", pass except: traceback.print_exc() try: clientsock.close() print "Connection has been closed." once = 1 # One connection has been made except KeyboardInterrupt: raise except: traceback.print_exc()