echo tcp-server

from socket import *
from signal import *
import time


# utility
identify = lambda addr: '%s:%d' % (addr)
local_id = identify
peer_id = identify
curr_time = lambda struct_time: '(%d-%d-%d %d:%d:%d)' % struct_time[:6]


# install handler for sigint
def sigint_handler(signum, frame):
global is_sigint_up
is_sigint_up = True
print 'interrupt signal is up...'

signal(SIGINT, sigint_handler)
is_sigint_up = False


# body code
host = '127.0.0.1'
port = 8000
serv_addr = (host, port)
backlog = 5
buff_size = 8192
listen_sock = socket(AF_INET, SOCK_STREAM)
listen_sock.bind(serv_addr)
listen_sock.listen(backlog)
print 'echo-server is running at (%s)' % local_id(serv_addr)

conn_sock = None
peer_addr = ''

while not is_sigint_up:
conn_sock, peer_addr = listen_sock.accept()
print 'request from %s   ...accepted' % peer_id(peer_addr)
print 'session with %s   ...started' % peer_id(peer_addr)
print

try:
  while True:
   recv_data = conn_sock.recv(buff_size) # except socket.error
   if not recv_data: break   # for tcp, receiving none data on blocking
                             # socket means that peer has closed.
   print peer_id(peer_addr), curr_time(time.localtime())
   print ' ', recv_data
   print
   
   conn_sock.sendall(recv_data) # except socket.error
   print local_id(serv_addr), curr_time(time.localtime())
   print ' ', recv_data
   print
   
  print 'session with %s ending   ...finished' % peer_id(peer_addr)

except error, (sock_error_no, sock_error_msg):
  conn_sock.close()
  print sock_error_msg + '!'
  print 'session with %s broken...' % peer_id(peer_addr)
  print
  
except KeyboardInterrupt: # KeyboardInterrupt has no-effect!
                           # KeyboardInterrupt is concerned to I/O.
  pass
  
finally:
  conn_sock.close()
  
  
listen_sock.close()
print 'echo-server has quited smoothly!\n'
raw_input('hit to quit...')