Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to close a socket and ObjectOutputStream?

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?

like image 210
Ben Page Avatar asked Mar 17 '09 12:03

Ben Page


People also ask

How do you close a socket connection?

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.

Should you close a socket after performing operations?

You should definitely close sockets if possible when you are done with them!

Should you close a socket Java?

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.


2 Answers

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();
like image 189
Jason Day Avatar answered Oct 25 '22 10:10

Jason Day


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.

like image 40
Avi Avatar answered Oct 25 '22 10:10

Avi