Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle Socket Disconnecting in Java? [duplicate]

Tags:

java

sockets

Hey all. I have a server written in java using the ServerSocket and Socket classes.

I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.

What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?

like image 626
Alex Avatar asked Jan 27 '09 23:01

Alex


1 Answers

Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).

Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.

like image 139
Rob Avatar answered Oct 03 '22 00:10

Rob