############################################################
##
## TCP Server Socket - By Fischetti P.
##
############################################################
##
## Serve + client contemporanemente.
## Ogni connessione avvia un Thread separato
##
############################################################

import socket
import time
import threading

def strTohex(s):
    lst = []
    for ch in s:
        hv = hex(ord(ch))
        lst.append(hv)
    return lst

class ClientThread(threading.Thread):
    def __init__(self,conn,ip,port):
        threading.Thread.__init__(self)
        self.conn=conn
        self.ip = ip
        self.port = port
        print "[+] New thread started for "+ip+":"+str(port)
  
    def run(self):
        while True:
            data = self.conn.recv(2048)
            if not data: break
            print "%s %d) received data:%s" % (self.ip,self.port, data)
            self.conn.send(data.upper())  # echo up
            
TCP_IP = '127.0.0.1'
TCP_PORT = 6000
BUFFER_SIZE = 1024
 
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

TCP_IP=socket.gethostname()
tcpsock.bind((TCP_IP, TCP_PORT))

threads = []
 
while True:
    tcpsock.listen(4)
    print "Waiting for incoming connections..."
    (conn, (ip,port)) = tcpsock.accept()
    newthread = ClientThread(conn,ip,port)
    newthread.start()
    threads.append(newthread)
 
for t in threads:
    t.join()


