How to tell if a socket client has disconnected?

6

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

The client connects and the connection is managed on a unique thread with infinite loop communication.

The problem when I drop the client or close the connection, I do not know how to implement on the server that the client has terminated the connection. I know that the connection is closed by itself, but the client socket object is still saved in List .

In short, I do not know when to call method remove of List .

I have tried to use the isConnected or isClosed method of the 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 it is 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 , so far it's working, I do not 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 Scanner was created as follows new Scanner(socket.getInputStream());

    
asked by anonymous 15.08.2015 / 04:23

2 answers

1

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

In your case, this behavior is occurring within the hasNextLine () call, which probably calls the InputStream readLine () and is blocking correctly while the connection is open, or immediately returns empty when the connection closes.

    
26.08.2015 / 08:09
1

A EOFException is posted if the client disconnects unexpectedly because the socket can no longer read data means an unexpected end .

You can see an example of a chat server that I made to answer the other question here on the OS using the above exception on the following link:

  

p>
    
15.01.2016 / 06:06