When I run the client, does the server shut down, why?

2

As soon as I run a Client, the Server connection terminates. The while block of the Attendant Class run () method does not execute. I ran a test and the running attribute is set to true. I can not figure out what's going on.

Server class.

public class Servidor implements Runnable{

private ServerSocket server; 
private boolean inicializado; 
private boolean executando;
private Thread thread;
private List<Atendente> atendentes; 

public Servidor(int porta) throws Exception{
    atendentes = new ArrayList<Atendente>();
    inicializado = false; 
    executando = false;

    open(porta);
}

private void open(int porta) throws Exception{
    server = new ServerSocket(porta);
    inicializado = true;
}

private void close(){

    for(Atendente atendente : atendentes){
        try{
            atendente.stop();
        }catch(Exception e){
            System.out.println(e);
        }
    }

    try{
        server.close();
    }catch(Exception e){
        System.out.println(e);
    }
    server = null;
    inicializado = false;
    executando = false;

    thread = null;
}

public void start(){

    if(!inicializado || executando){
          return;
    }

    executando = true;

    thread = new Thread(this);
    thread.start();
}


public void stop() throws Exception{
    executando = false; 
    if(thread != null){
        thread.join();
    }
}

public void run() {

    System.out.println("Aguardando conexão");

    while(executando){
        try{
            server.setSoTimeout(2500); 

            Socket socket = server.accept();

            System.out.println("Conexão estabelecida");

            Atendente atendente = new Atendente(socket);
            atendente.start();
            atendentes.add(atendente);
        }catch(SocketTimeoutException e){
            //ignorar

        }// no caso de qualquer outra execeção, a consideramos fatal, forçando o enecerramento do laço
        catch(Exception e){
            System.out.println(e);
            break;
        }
    }
    close();
}


public static void main(String[] args) throws Exception{ 

    System.out.println("Inciando Servidor");

    Servidor servidor = new Servidor(2525);
    servidor.start();

    System.out.println("Pressione ENTER para encerrar o Servidor");
    new Scanner(System.in).nextLine();

    System.out.println("Encerrando Servidor");

    servidor.stop();

}

}

Class attendant.

public class Atendente implements Runnable{

private Socket socket;
private BufferedReader in;
private PrintStream out;
private boolean inicizalido;
private boolean executando;
private Thread thread;

public Atendente(Socket socket) throws Exception{
    this.socket = socket;
    this.inicizalido = false;
    this.executando = false;

    open();
}


private void open() throws Exception{

    try{
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintStream(socket.getOutputStream());
        inicizalido = true;
    }catch(Exception  e){
        close();
        throw e;
    }
}

private void close(){
    //tomando cuidado de testar se o atruibuto foi ou não corretamente inicializado no metodo open().
    if(in != null){
        try{
            in.close();
        }catch(Exception e){
             System.out.println(e);
        }
    }

    if(out != null){
        try{
            out.close();
        }catch(Exception e){
             System.out.println(e);
        }
    }

    try{
        socket.close();
    }catch(Exception e){
         System.out.println(e);
    }

    in = null;
    out = null;
    socket = null;
    inicizalido = false;
    executando = false;
    thread = null;
}

public void start(){
    if(!inicizalido || executando){
        return;
    }

    executando = true; 
    thread = new Thread(this);
    thread.start();
}

public void stop() throws Exception{
    executando = false;
    if(thread !=  null){
        thread.join();
    }
}

@Override
public void run() {

    while(executando){
        try{
             socket.setSoTimeout(2500);
            String menssagem =  in.readLine();
            //Incluiremos a porta de conexaão do cliente para diferenciá-los durante a execução
            System.out.println("\nMenssagem Recebida do Cliente [ " 
                         + socket.getInetAddress().getHostName() +
                         ": " + 
                         socket.getPort() +
                         "]: " +
                        menssagem);


            if(menssagem.equals("FIM")) break;

            out.println(menssagem);
        }catch(SocketTimeoutException so){
             //ignorar
        }catch(Exception e){ // se alguma outra exceção ocorrer, forçamos o encerramento do atendimento
            System.out.println(e);
            break;
        }

        System.out.println("Encerrando Conexão");
        close();
    }
}

}

Client Class.

public class Cliente {

public static void main(String[] args) throws Exception{

    System.out.println("Inciando Cliente");

    System.out.println("Iniciando conexão com o servidor");

    Socket socket = new Socket("localhost",2525);

    System.out.println("Conexão establecida");

    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();

    BufferedReader in = new BufferedReader(new InputStreamReader(input));

    PrintStream out = new PrintStream(output);

    Scanner scanner = new Scanner(System.in);

    while(true){
        System.out.print("Digite uma menssagem : ");
        String menssagem = scanner.nextLine();

        out.println(menssagem);

        if("FIM".equals(menssagem)){
            break;
        }

        menssagem = in.readLine();

        System.out.println(
                "Menssagem recebida do servidor: "
        + menssagem); 
    }

    System.out.println("Encerrando conexão");
    in.close();
    out.close();
    socket.close(); 
}

}

I have not yet implemented the client threads. But it does not matter to run the program. As a result, you would have to display different Client connection ports.

    
asked by anonymous 26.08.2014 / 00:14

1 answer

2

The problem and after analyzing and testing the code and in direct response to the problem put, in the class "Attendant" the code excerpt:

System.out.println ("Terminating Connection"),
close ();

It has to be placed outside the "while" loop and the result will be expected ie at the first connection it will not be closed but will wait for new client communication.

    
26.08.2014 / 17:49