import java.net.ServerSocket;
import java.net.Socket;

import java.util.Scanner;

import java.io.InputStream;
import java.io.OutputStream;

public class EchoServer {
	private ServerSocket main;
	
	EchoServer(int port) throws java.io.IOException {
			main = new ServerSocket(port);
			System.out.println("Serveur:"+port);
	}
	
	void echo() throws java.io.IOException {
		System.out.println("Attente d'un client");
		Socket client = main.accept();
		if (client == null) return;
		
		System.out.println("Connexion du client");
		InputStream input = client.getInputStream();
		OutputStream output = client.getOutputStream();
		
		// lit les octets 100 par 100
		byte[] buffer = new byte[100];
		do {
			int nb = input.read(buffer);
			if (nb == -1) break;	
			System.out.println(nb+" octets recus!");

			output.write(buffer);
			System.out.println(nb+" octets renvoyes!");
		} while(true);
		pause(10000);	
		//client.close();
	}
	
	void close() throws java.io.IOException {
		//main.close();
	}
	static public void pause(int value) {
		long init = System.currentTimeMillis();
		while ((System.currentTimeMillis()-init)<value) ;	
	}
	static public void main(String[] params) {
		try {
			int port = 1000;
			if (params.length!=0) port = Integer.parseInt(params[0]);
			EchoServer serveur = new EchoServer(port);
			for(int i=0; i<5; i++) {
				serveur.echo();
			}
			serveur.close();
		} catch (java.io.IOException ioe) {
			System.err.println("Exception : "+ioe);
			ioe.printStackTrace(System.err);
		}
	}
}
