#! /usr/bin/python2
""" One connection only but handles lines correctly.
Uses socket makefile """
__author__ = "brock"

import socket

PORT = 40373

def handleclient(clientsock):
    """ client handler """
    linecount = 0
    status = True
    clientin = clientsock.makefile('r')
    clientout = clientsock.makefile('w')
    try:
        data = clientin.readline()
        while data:
            if data[-1:] == '\n':
                data = data[:-1]
            linecount = linecount + 1
            clientout.write("{1}: {0}\r\n".format(data, linecount))
            clientout.flush()
            data = clientin.readline()
    except EOFError:
        status = False
    clientin.close()
    clientout.close()
    clientsock.close()
    return status

def main():
    """ main routine """
    try:
        rendezvous = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ## Do not do the next line....
        rendezvous.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        rendezvous.bind(('', PORT))
        print 'Running on port {0}'.format(PORT)
        rendezvous.listen(1)
        clientconn, clientaddr = rendezvous.accept()
        print 'Connected to {0}'.format(clientaddr)
        handleclient(clientconn)
    except (EOFError, KeyboardInterrupt):
        pass

if __name__ == "__main__":
    main()
