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());