#! /usr/bin/python2
""" Multiple connections with threaded server
Overriding threading.Thread
Uses locking """
__author__ = "brock"

import socket
import threading

PORT = 40373

class ThreadClient(threading.Thread):
    """ thread client """
    def __init__(self, clientsock, linecount, linelock):
        threading.Thread.__init__(self)
        self._clientsock = clientsock
        self._linecount = linecount
        self._linelock = linelock
        self.daemon = True
    def run(self):
        status = True
        clientin = self._clientsock.makefile('r')
        clientout = self._clientsock.makefile('w')
        try:
            data = clientin.readline()
            while data:
                if data[-1:] == '\n':
                    data = data[:-1]
                self._linelock.acquire()
                self._linecount[0] = self._linecount[0] + 1
                self._linelock.release()
                clientout.write("{1}: {0}\r\n".format(data, self._linecount[0]))
                clientout.flush()
                data = clientin.readline()
        except EOFError:
            status = False
        clientin.close()
        clientout.close()
        self._clientsock.close()
        return status

def main():
    """ main routine """
    linelock = threading.Lock()
    linecount = [0]
    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)
        while 1:
            clientconn, clientaddr = rendezvous.accept()
            print 'Connected to {0}'.format(clientaddr)
            childthr = ThreadClient(clientconn, linecount, linelock)
            childthr.daemon = True
            childthr.start()
    except (EOFError, KeyboardInterrupt):
        pass

if __name__ == "__main__":
    main()
