Search code examples
javasocketschatserversocket

Java Socket Termination for chatting service


I'm learning about Java sockets, so I attempted to write two separate programs (a server side and a client side), and using swing to create a simple chatting program. Now the program works fine, I can see text sent from client-server and vice versa. However, the problem is when I terminate the connection from the server side.

I understand that the two sockets are not necessarily related in way that if the connection is terminated at the server side, the client doesn't know about it, and keeps throwing IOExceptions at ObjectInput/OutputStreams.

My question is, is there a way to notify the client about the server terminating the connection or should I accept the fact that the connection has to be terminated from the client side first?


Solution

  • If you're reading and the peer closes the connection:

    1. read() will return -1
    2. readLine() will return null
    3. readObject(), readInt(), and all other readXXX() methods will throw EOFException.