#!/usr/bin/env python
# tcpclient2.py -- a single threaded TCP client with sockets

import socket

BLOCKSIZE = 1024

def create_client(host, port):
    "Connect to a server, send input, and print whole server reply"
    
    send_data = read_data_from_user()
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    s.sendall(send_data)
    s.shutdown(socket.SHUT_WR)
    
    while True:
        buf = s.recv(BLOCKSIZE)
        if not buf:
            break
        print buf,
    
    s.close()

def read_data_from_user():
    "Read data from user and return as string"
    print "Enter a line to send to server. Terminate with ~."
    data = []
    while True:
        inp = raw_input('? ')
        if inp == '~.':
            break
        data.append(inp)
    return '\r\n'.join(data) + '\r\n'

if __name__ == '__main__':
    import sys
    if len(sys.argv) != 3:
        print >>sys.stderr, "Usage:", sys.argv[0], "host port"
        sys.exit(1)
    host, port = sys.argv[1], int(sys.argv[2])
    
    create_client(host, port)
