import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPEchange {
	
	public static void envoiTCP(Utilisateur User1,Utilisateur User2, String Msg ) {
		MessageHorodate mh =  new MessageHorodate(User1, User2, Msg);
		try {
            Socket s = new Socket(User2.getIp(), User2.getPort());
            PrintStream output = new PrintStream(s.getOutputStream());
            output.println(mh.toString());
            output.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	public static void ecouteTCP() {
		try {
			ServerSocket ss = new ServerSocket(1234);
	        while(true) {
	        	System.out.println("Attente Session de clavardage");
	        	Socket link = ss.accept();
	        	new Thread(new RunnerTCP(link)).start();
	            }
	        } 
		catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
}

class RunnerTCP implements Runnable {
		final Socket link;

	    public RunnerTCP(Socket link) {
	        this.link = link;
	    }

	    @Override
	    public void run() {
	        System.out.println("Thread started");
	        try {
	            InputStream is = link.getInputStream();
	            int rcv = 0;
	            while ((rcv = is.read()) != -1) {
	                System.out.println("Received: "+ rcv);
	            }
	            System.out.println("Finishing thread");
	            is.close();
	            link.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
}
