echo tcp-client

from socket import *
from signal import *
from time import *

# utility
identify = lambda addr: '%s:%d' % addr
local_id = identify
serv_id = identify
curr_time = lambda time_struct=localtime(): '%d-%d-%d %d:%d:%d' % time_struct[: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)

# main body
serv_ip = '127.0.0.1'
serv_port = 8000
serv_addr = (serv_ip, serv_port)
buff_size = 8192

conn_seconds = 0
is_sigint_up = False
print 'try to connect to echo-server %s...' % serv_id(serv_addr),
connect_again = False # connect to server again

while not is_sigint_up:

if connect_again:
  print 'try to connect to echo server(%s:%d)...' % (serv_ip, serv_port),
  connect_again = False
  
# connect to server
conn_sock = socket(AF_INET, SOCK_STREAM)
errno = conn_sock.connect_ex((serv_ip, serv_port))

if errno == 0:   #succeed on connection
  conn_seconds = 0
  print '\nnew session with %s has started.' % serv_id(serv_addr)
else:
  conn_seconds += 1
  if conn_seconds > 10:
   print '\nconnection is overtime!'
   break
  
  remain_time = '%2d sec' % (10 - conn_seconds),
  print remain_time,
  sleep(1)
  print '\b'*(len(remain_time) +2 ),
  continue
  
# session with server
try:
  while True:
   line = raw_input('send: ') # except KeyboadrInterrupt
   if len(line) == 0: continue
   conn_sock.sendall(line)  # except socket.error
   print
   print local_id(conn_sock.getsockname()), curr_time()
   print ' ', line
   
   recv_data = conn_sock.recv(buff_size) # except socket.error
   print serv_id(serv_addr), curr_time()
   print ' ',recv_data
   print '\n\n'
   
except KeyboardInterrupt:
  print '\ncatch KeyboardInterrupt...'
  is_sigint_up = True
  
except error:
  print '\nsession with %s:%d is broken!' % (serv_ip, serv_port)
   
finally:
  conn_sock.close()
  connect_again = True
  
raw_input('hit to quit...')