Search code examples
javasocketsnetworkingserverobjectinputstream

ObjectInputStream throws EOFException after repeated use of readUTF()


I am trying to implement a server client communication and want to keep toe connection open until the client terminates it, therefore it's running in a loop. The first iteration works fine however in the second run through of the loop client.getOis().readUTF(); throws an exception.

This is the serverside code:

  try {
        client.setOis(new ObjectInputStream(client.getSocket().getInputStream()));
        client.setOos(new ObjectOutputStream(client.getSocket().getOutputStream())); 

        while (active) {
            String client_msg = client.getOis().readUTF();
            String action = client_msg.split(";")[0];
            String leftover = client_msg.split(";")[1];

            switch (action) {
                case "LOGIN": login(action, leftover);break;
                case "SEND": send(leftover);break;
                case "DISCONNECT": update(action);break;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

The client just sends over a simple string "LOGIN;username", which the login method handles.

This is the exception:

java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.ObjectInputStream$BlockDataInputStream.readUnsignedShort(ObjectInputStream.java:3170)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:3226)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1133)
at gruber.middleware.ClientHandler.run(ClientHandler.java:26)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Solution

  • The problem was that I opend the Socket and the Streams in a try-with-resources which meant they were closed automatically.