重复使用 readUTF() 后,ObjectInputStream 抛出 EOFException

ObjectInputStream throws EOFException after repeated use of readUTF()

我正在尝试实现服务器客户端通信,并希望保持脚趾连接打开直到客户端终止它,因此它处于循环中 运行ning。第一次迭代工作正常,但是在循环 client.getOis().readUTF(); 的第二个 运行 中抛出异常。

这是服务器端代码:

  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();
    }

客户端仅发送一个简单的字符串 "LOGIN;username",登录方法将处理该字符串。

这是例外情况:

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)

问题是我在 try-with-resources 中打开了 Socket 和 Streams,这意味着它们会自动关闭。