views:

1141

answers:

3

Hi all,

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?

+1  A: 

Maybe this tutorial from Javaworld can help you.

boutta
+1  A: 

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.

Avi
+3  A: 

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();
Jason Day
Thanks, I never thought to notify my program of the quitting, I guessed the TCP would do that.I think as Avi said it was that I was waiting for input while I closed the socket, by alerting the client i can tell it to stop waiting for input.
Ben Page