So, I wrote a thread on my client side that is trying to readObject() from the socket stream.
This thread runs for as long as the client is connected.
The connection to the server can be closed on the client GUI. If the client decides to disconnect (this will not exit the client program) by clicking "disconnect", the socket will be closed and isConnected false.
Since the client read stream is trying to readObject() from the stream, and the connection can be closed through the GUI, I set the timeout to 250 ms ( setSoTimeout(250) ).
@Override public void run() { this.connection = this.connectionHandler.getSocket(); while(connectionHandler.isConnected()) { this.readCircle(); } this.connectionHandler.setReadTaskRunning(false); } private void readCircle() { try { this.connection.setSoTimeout(250); this.connectionHandler.readData();
}
I know that readObject() will block, and to check if the client is still connected, I put it in a while , which checks (every timeout) if the client socket is still connected.
My question is now:
In case readObject() starts to receive the object transmitted by the server, tries to read it, but when processing the timeout, the data in the stream will be “damaged” somehow because it is canceled, Or I should just leave the readObject() block and catch the exception if the GUI thread wants to close the socket.
I am not very experienced with sockets, and maybe my approach is wrong.
source share