import socket 
from threading import Thread 
from SocketServer import ThreadingMixIn 
import json
import heapq
# Multithreaded Python server : TCP Server Socket Thread Pool
class ClientThread(Thread): 
 
    def __init__(self,ip,port): 
        Thread.__init__(self) 
        self.ip = ip 
        self.port = port 
        print "[+] New server socket thread started for " + ip + ":" + str(port) 
 
    def run(self): 
        while True : 
            data = conn.recv(2048) 
            print "Server received data:",data
            loaded_r = json.loads(data)
            lista_max = []
            for i in range(0,3):
               name = 'g'+str(i)
               l = list(loaded_r[name])
               lista_max = lista_max + l
            print " 3 maiores temperaturas"
            list_larger = heapq._nlargest(3,lista_max)
            F = open('larger.txt','w') 
            for i in range(0,3):
                for j in range(0,len(list_larger)):
                    name = 'g'+str(i)
                    if list_larger[j] in loaded_r[name]:
                        F.write(name)
                        print name
            F.close()
                        
            MESSAGE = raw_input("Multithreaded Python server : Enter Response from Server/Enter exit:")
            if MESSAGE == 'exit':
                break
    
# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = '0.0.0.0' 
TCP_PORT = 2004 
BUFFER_SIZE = 20  # Usually 1024, but we need quick response 
 
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
tcpServer.bind((TCP_IP, TCP_PORT)) 
threads = [] 
 
while True: 
    tcpServer.listen(4) 
    print "Multithreaded Python server : Waiting for connections from TCP clients..." 
    (conn, (ip,port)) = tcpServer.accept() 
    newthread = ClientThread(ip,port) 
    newthread.start() 
    threads.append(newthread) 
 
for t in threads: 
    t.join() 