gpt4 book ai didi

java - ObjectInputStream 异常

转载 作者:行者123 更新时间:2023-11-29 03:53:23 24 4
gpt4 key购买 nike

我有三个类,客户端、服务器和处理程序(将处理服务器连接),如下所示:

// The Client
public void sendSomePackage() {
try {
socket = new Socket("localhost", 54321);
sos = socket.getOutputStream();
oos = new ObjectOutputStream(sockOutput);
} catch (IOException e) {
e.printStackTrace(System.err);
return;
}

// About to start reading/writing to/from socket

try {
Package package = new Package(100);
oos.writeObject(pacote);

} catch (IOException e) {
e.printStackTrace(System.err);
}

try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}

// Done reading/writing to/from socket, closing socket.

try {
sock.close();
} catch (IOException e) {
System.err.println("Exception closing socket.");
e.printStackTrace(System.err);
}
//Exiting
}

现在是服务器类:

// The Server - with a method that just wait for connections

public void waitForConnections() {
while (true) {
try {
socket = serverSocket.accept();

// Server:Accepted new socket, creating new handler for it
SimpleHandler handler = new SimpleHandler(socket);
handler.start();

// Server:Finished with socket, waiting for next connection
}
catch (IOException e){
e.printStackTrace(System.err);
}
}
}

我的处理程序,它只处理服务器连接:

@Override
public void run() {
//Handler: Handler run() starting
while (true) {
try {
package = (Package) ois.readObject();
if (pacote != null) {
System.out.println("Package received " + pacote.getSourceid());
}
} catch (Exception e) {
e.printStackTrace(System.err);
break;
}
}

try {
// SimpleHandler:Closing socket
sock.close();
ois.close();
} catch (Exception e) {
// Handler: Exception while closing socket, e=" + e);
e.printStackTrace(System.err);
}

}

想法是客户端向我的服务器发送一些“包”对象,服务器将继续运行以随时接收“包”对象。连接工作正常,但在程序结束时启动异常,这是一个:

Package received 100
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at br.ufscar.socket.SimpleHandler.run(SimpleHandler.java:45)
at java.lang.Thread.run(Unknown Source)

我已经在 Google 上搜索过一些东西,但目前还没有。有什么想法吗?

最佳答案

这完全符合您的要求(可能)。它读取 100 然后再次通过循环(while(true) 永远不会停止循环直到 break 语句)并抛出异常,因为没有发送更多数据并且它进入 catch 语句并在退出 while 循环之前打印错误.

关于java - ObjectInputStream 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699975/

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