package br.senacpos.turma02;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class listagem1 {

	public static void main( String[] args ) {;

	int port = 5000;

	if ( args.length > 1 ) {
		System.err.println( "Uso: java listagem1 [porta-default=5000]" );
		System.exit(1);
	}
	else if( args.length == 1) {
		try {
			port = Integer.parseInt( args[0] );
		}
		catch( NumberFormatException exc ) {
			System.err.println( args[0] + " nao e um numero valido!" );
			System.exit(2);
		}
	}
	System.out.println( "Parametro porta = " + port );

	ServerSocket server = null;

	try {
		server = new ServerSocket( port );
	}
	catch( IOException exc ) {
		System.err.println( "erro ao criar socket na porta " + port + ": " +
				exc.getMessage() );
		exc.printStackTrace();
		System.exit(3);
	}

	// Espera conexao do cliente
	try {
		Socket socket = server.accept();
		System.out.println( "conexao recebida de " + socket.getInetAddress() );
		// codigo para tratar conexao aqui
		talkToClient(socket);

	} catch( IOException exc ) {
		System.err.println( "erro aceitando conexoes: " + exc.getMessage() );
		exc.printStackTrace();
		System.exit(4);
	} finally {
		try {
			server.close();
		} catch( IOException exc ) {
			System.err.println( "erro fechando socket: " + exc.getMessage() );
			exc.printStackTrace();
			System.exit(5);
		}
	}
	}
	private static void talkToClient( Socket clientSocket ) {
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

			String inputLine, outputLine;

			System.out.println( "vai ler mensagem do client <- " + clientSocket.getInetAddress() );
			if( (inputLine=in.readLine()) != null ) {
				System.out.println( "mensagem do client: " + inputLine );
			}

			System.out.println( "envia mensagem para o client -> " + clientSocket.getInetAddress() );
			outputLine = "bye";
			out.println(outputLine);

			out.close();
			in.close();
			clientSocket.close();
			out.close();
		} catch( IOException ex ) {
			System.err.println( "erro fechando socket: " + ex.getMessage() );
			ex.printStackTrace();
			System.exit(6);
		}
	}
}
