#!/usr/bin/python -tt

import sys
import socket 

HOST = ''
PORT = 0
N = 0

def main():
  if len(sys.argv) != 3:
    print('usage: ./server.py port N')
    sys.exit(1)

  PORT = int(sys.argv[1])
  N = int(sys.argv[2])

  #Socket: create a new connection endpoint
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  #Bind: Attach a local address to a socket
  s.bind((HOST, PORT))

  #Listen: Announce willingness to accept N connections
  s.listen(N)	# listen to max N queued connection

  while 1: # Forever
    #Accept: Block until request to establish a connection
    (conn, addr) = s.accept() # returns new socket + addr client     
    print 'Connection established with', addr

    #Receive: Receive data over a connection
    data = conn.recv(1024) 
    if data:
      if data.lower() == 'exit':
        #Send: Send the exit message
        conn.send('server exitted!')
        conn.close()        
        print 'Exit message received, exitting the server...'
        break
      #Send: Send data back
      conn.send(data)
      print 'Echoed the message:', data

    #Close: Release the connection
    conn.close()
    print 'Connection closed with', addr

if __name__ == '__main__':
    main()
