package nslookup; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.HashMap; import java.util.Map; public class ServerThread extends Thread { Map<String,InetAddress> cache = null; Socket s = null; public ServerThread(Map<String,InetAddress> c, Socket ts) { cache = c; s = ts; } public void run() { try { System.out.println("ServerThread started"); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); Object o = ois.readObject(); if(o instanceof NameQuery) { // trattamento della richiesta NameQuery nq = (NameQuery) o; String hostName = nq.getHostname(); System.out.println("Looking up "+hostName); if(cache.containsKey(hostName) && nq.getCached()) { System.out.println(hostName+" gia' in cache con indirizzo "+cache.get(host Name)); } else { // host non in cache o cached false if(cache.containsKey(hostName)) { // se c'era, cancellalo prima di reineri rlo InetAddress ia = cache.get(hostName); cache.remove(hostName); System.out.println("Cancellata entry cache <"+hostName+","+ia+">") ; } InetAddress ia = InetAddress.getByName(hostName); cache.put(hostName, ia); System.out.println("Aggiunto in cache: <"+hostName+","+ia+">"); } // adesso invia la risposta ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); QueryAnswer qa = new QueryAnswer(hostName,cache.get(hostName)); oos.writeObject(qa); return; } else { // tipo non previsto, restituisce un messaggio di errore ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); System.out.println("Tipo imprevisto per l'oggetto letto"); QueryAnswer qa = new QueryAnswer(); oos.writeObject(qa); return; } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("Non trovo la class per l'oggetto letto"); return; } } }