I am writing a networked application in Java, to communicate between the client and the server I am using serialized objects to represent data/commands and sending them through object output/input streams.
I am having problems cleanly closing the connections, I assume that I am missing something fundamental that I do not really know about, I've never used sockets with serialization before.
What ever order I try to shutdown the connection (close client first, close server first) a ConnectionReset
exception is thrown. I cannot catch this exception as the client runs in another thread to the rest of the program constantly listening for messages, this must be done, as in Java socket.read()
is a blocking method.
What is the correct way to close a socket that I am using to send objects?
close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.
You should definitely close sockets if possible when you are done with them!
The finalize() method is called by the Java virtual machine ( JVM ) before the program exits to give the program a chance to clean up and release resources. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation.
You need to send your listener (whether client or server, it doesn't matter) some kind of signal to stop listening for more data. Here is a very simple example:
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));
while (true) {
Object obj = ois.readObject();
if (obj instanceof String) {
if ((String)obj).equalsIgnoreCase("quit")) {
break;
}
}
// handle object
}
ois.close();
sock.close();
You should probably not be waiting to read() from a socket, while the other end is closing it. In a good network protocol, the client can inform the server that it has nothing more to write (maybe by sending it a special close character) before closing the connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With