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());
Related: It is possible to know how many clients are connected to Serversocket?
– Guilherme Nascimento