gpt4 book ai didi

java - 重用 ObjectInputStream 会抛出 StreamCorruptedException

转载 作者:行者123 更新时间:2023-12-04 15:50:57 26 4
gpt4 key购买 nike

我有一个客户端-服务器应用程序。客户端发送一个对象,服务器发回相同的对象,这是一个简单的回显服务器。如果我为每个新请求创建一个新的 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();

客户端

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

关于java - 重用 ObjectInputStream 会抛出 StreamCorruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com