How do I know if a socket client has disconnected?

Asked

Viewed 1,129 times

6

I have a server that has a List with all connected clients.

Client connects and connection is managed in a unique thread with infinite communication loop.

The problem when I drop the client or close the connection, I do not know how to implement on the server that the client closed the connection. I know the connection closes on its own, but the client’s socket object is still saved on List.

In short, I don’t know when to call the method remove of List.

I’ve tried the method isConnected or isClosed socket. It did not work.

UPDATE

I’m doing it this way and it’s working.

@Override
public void run() {

    //loop espera mensagem do client
    while(true){
        //aguarda receber uma mensagem
        String response = receive();
        //condição para encerrar comunicação
        if(response==null)
            break;
        //valida mensagem
        Message msg;
        try{
             msg = new Gson().fromJson(response, Message.class);
        }catch(Exception e){
            //mensagem invalida, volta ao inicio do laço e espera nova mensagem.
            continue;
        }            
        //cria thread para tratar mensagem
        new Thread(new Runnable(){
            @Override
            public void run() {
                managerMessage(msg);
            }
        }).start();
    }
    System.out.println("Cliente desconectou");
    //remove socket da lista de conexões abertas
    server.removeConnection(this);

}

The receive() method I created keeps waiting for a message from the client, while not receiving a message the method does not complete. I noticed that when I drop the client, receive() starts to return null, for now it’s working, I don’t know if it’s the best way.

public String receive(){
    //espera receber mensagem
    while(receiver.hasNextLine())
        return receiver.nextLine();//quando um mensagem chega retona
    return null;
} 

Obs.: receiver is a Scanner was created as follows new Scanner(socket.getInputStream());

2 answers

1

1

The right time to consider the closed connection is when Inputstream returns nothing when read. While the connection is open, read() blocks until at least one byte can be returned, and readline() blocks until it receives an entire line.

In your case, this behavior is happening within the call to hasNextLine(), which probably calls the readline() of Inputstream and is locking correctly while the connection is open, or immediately returns empty when the connection closes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.