package instantMessanger; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; public class Messanger { /** * @param args */ public static void main(String[] args) { final int PORTA = 17191; final int DELAY = 5000; final int VARIA = 1000; ServerSocket ss = null; try { ss = new ServerSocket(PORTA); } catch (IOException e) { System.out.println("Errore nella creazione del serverSocket"); return; } int timeout = DELAY + ((int) Math.random()*VARIA); try { ss.setSoTimeout(timeout); } catch (SocketException e) { System.out.println("Non riesco a mettere un timeout sul socket"); System.out.println(e.getCause()); } Socket s = null; while(true) { try { s = ss.accept(); System.out.println("Sono il server"); break; // se ci riesco esco dal ciclo } catch (SocketTimeoutException e) { System.out.println("timeout scattato"); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } try { s = new Socket(args[0],PORTA); System.out.println("Sono il client"); break; // se ci riesco esco dal ciclo } catch (UnknownHostException e) { System.out.println("Nome dell'host errato: "+args[0]); return; } catch (IOException e) { System.out.println("host remoto non risponde"); } } System.out.println("Connessione stabilita"); CopyThread leggi = null; CopyThread scrivi = null; try { leggi = new CopyThread(s.getInputStream(),System.out,"da remoto"); scrivi = new CopyThread(System.in,s.getOutputStream(),"per remoto"); leggi.start(); scrivi.start(); } catch (IOException e) { e.printStackTrace(); } try { leggi.join(); System.out.println("Thread socket -> video terminato"); scrivi.join(); System.out.println("Thread tastiera -> socket terminato"); } catch (InterruptedException e) { e.printStackTrace(); } } }