重用 ObjectInputStream 会抛出 StreamCorruptedException

Reusing ObjectInputStream throws StreamCorruptedException

我有一个客户端-服务器应用程序。客户端发送一个对象,服务器发回相同的对象,这是一个简单的回显服务器。如果我为每个新请求创建一个 Client 的新实例,下面的代码就可以正常工作。但是,如果我使用客户端的现有实例,它会给我一个 java.io.StreamCorruptedExceptionjava.lang.ClassCastException

客户

Socket socket = new Socket(hostName, port);


in = new ObjectInputStream(
            new BufferedInputStream(socket.getInputStream()));
out = new ObjectOutputStream(socket.getOutputStream());

//calling this each time I have a new request
out.writeObject(request);
out.flush();
Object object = in.readObject();

服务器

ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
new Thread(new ClientWorker(clientSocket)).start();

ClientWorker

public void run() {
        try {
            ObjectOutputStream out =
                    new        ObjectOutputStream(clientSocket.getOutputStream());

            ObjectInputStream in = new ObjectInputStream(
                    new BufferedInputStream(clientSocket.getInputStream()));

            Object inputObject;

      while(true) {
            while ((inputObject = in.readObject()) != null) {
                  out.writeObject(inputObject);
            }

            out.flush();
        }
    } catch (IOException e) {
            e.printStackTrace();
    } catch (ClassNotFoundException e) {
            e.printStackTrace();
    }
}

编辑:

当下面的代码在复用的Client中执行时

in.readObject();

我得到异常

java.io.StreamCorruptedException: invalid type code: 00 at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1497) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1748) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1327) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:349)

在我对输入和输出对象流进行同步后问题得到解决。

synchronized(this) {
    while ((inputObject = in.readObject()) != null) {
        out.writeObject(inputObject);
    }
}

synchronized(this) {
   out.writeObject(request);
   out.flush();
   Object object = in.readObject();
}