gpt4 book ai didi

java - 在 Java 中使用 InputStreamReader 时出错

转载 作者:行者123 更新时间:2023-12-01 14:37:57 24 4
gpt4 key购买 nike

我尝试从客户端向服务器发送一个 int 值。这是我在下面使用的客户端代码:

_port   = 8071;
_socket = new Socket("localhost", _port);

Random rand = new Random();
int n = rand.nextInt(50) + 1;
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream());
dos.writeInt(n);
dos.flush();

服务器代码

try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

ObjectInputStream in = null;
in = new ObjectInputStream(socket.getInputStream());
int ClientNumber= in.readInt();
System.out.println(ClientNumber);
}

但我收到无效的流 header 错误。

invalid stream header: 0000002B at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:781) at java.io.ObjectInputStream.(ObjectInputStream.java:278) at ServiceRequest.run(ServiceRequest.java:24) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:680)

有谁知道这个错误是什么原因造成的吗?我的代码设置不正确吗?

最佳答案

您使用DataOutputStream写入并使用ObjectInputStream读取。您应该使用DataInputStream相反:

// Note declaration and assignment in a single statement. There's no point in
// making it null first.
DataInputStream in = new DataInputStream(socket.getInputStream());

// Note use of camelCase for variable name
int clientNumber = in.readInt();

您还应该在这里删除input:您没有从中读取内容,并且由于这看起来像是二进制数据流,因此不适合处理它作为文本。

哦,您应该在 finally block 中关闭输入流。

关于java - 在 Java 中使用 InputStreamReader 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304491/

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