Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sockets: check if client is able to receive message from server

Tags:

java

sockets

When I flush() the message from the server's OutputStream, the client either received message or not (if it was disconnected before timeout). I need to somehow control this situation from server-side, I have to know if client is able to receive the message before sending it. How it could be done?

like image 222
justasd Avatar asked Mar 08 '26 21:03

justasd


1 Answers

In the past, I have typically used a blocking read in a separate thread to read client messages and disseminate them as needed.

If the client disconnects, the InputStream.read() operation returns -1 and we take that as notification that the client has "disconnected" and the InputStream should be closed. It may also throw an IOException if the connection is abnormally terminated.

You can then test Socket.isClosed() to verify whether or not you can still write messages.

like image 70
Steve C Avatar answered Mar 10 '26 11:03

Steve C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!