Search code examples
javasocketsconnectionobjectinputstream

Java: Socket close connection and ObjectInputStream


My code looks like this, this is Server code (Runnable)

public void run() {
    while (true) {
        try {
            System.out.println("Waiting for client...");
            this.socket = serverSocket.accept();
            System.out.println("Client accepted");
            while (true) {
                readCommand();
                try {
                    Thread.sleep(2);
                } catch (Exception e) {
                }
            }
        } catch (Exception ex) {
            Main.error("Server stopped for current host", ex);
        }
    }
}

My problem is: when the client closes the connection, he still waiting to read the command in readCommand(); until a command was sent and an EOFException will be thrown. This is my readCommand method:

private void readCommand() throws Exception {
    Object o = new ObjectInputStream(socket.getInputStream()).readObject();
    if (o instanceof Command) {
        ((Command) o).execute();
        return;
    }
    if (o instanceof Recorder) {
        System.out.println("Recording received");
        ((Recorder) o).executeRecord();
        return;
    }
    if (o instanceof MyKeyEvent) {
        ((MyKeyEvent) o).execute();
        return;
    }
}

So I think before reading it has to check if the connection is open.

Edit: If I evaluate the run-method code, the EOFException is thrown in the try-catch-body. But he stops accepting clients.


Solution

  • An EOFException is exactly what I'd expect if the client closes the connection. So I'm not quite sure what your problem actually is. Perhaps you need to distinguish between an expected client disconnect and an unexpected client disconnect. In which case you should perhaps send some sort of End-of-message object to mark the end of transmission ?

    If you want to check if info is available, there's an available() method on the stream. I don't think you need your Thread.sleep(2), btw, since I would expect a read on a valid input stream to hang in the absence of data.