gpt4 book ai didi

尝试执行 java 套接字操作时出现 java.io.EOFException

转载 作者:行者123 更新时间:2023-11-29 08:11:54 25 4
gpt4 key购买 nike

对于下面包含的代码,我得到以下异常。 当 while() 循环被排除时,这工作正常。这是为什么?

Oct 6, 2011 1:19:31 AM com.mytunes.server.ServerHandler run
SEVERE: null
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2552)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at com.mytunes.server.ServerHandler.run(ServerHandler.java:68)

类服务器处理程序:

public class ServerHandler extends Thread {
.
.
.

public ServerHandler(...){
...
}


public void run(){

try {

os = s.getOutputStream();
oos = new ObjectOutputStream(os);

is = s.getInputStream();
ois = new ObjectInputStream(is);

while(true){

msg = (Messenger) ois.readObject();

String methodType = msg.getKey();

//validating various data passed from the serialized object
if(methodType.equals("validateCard")){

} else if(methodType.equals("validatePIN")){

}

}

} catch (SQLException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} finally{
try {
ois.close();
is.close();
oos.close();
os.close();
s.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}



}

类服务器

public class Server{

...
ServerSocket ss;
...

public static void main(String args[]){
Server server = new Server();
server.init();

}

public void init(){
try {
System.out.println("Server started...");

ss = new ServerSocket(port);

System.out.println("Listening on " + ss.getInetAddress() + ":" + ss.getLocalPort());

System.out.println("Waiting for clients...");

while(true){
Socket incoming_socket = ss.accept(); // returns a Socket connection object if received
new ServerHandler(...).start();
}

} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}


}

最佳答案

您一直永远尝试读取对象,永远不会跳出循环。当客户端关闭连接时,流将用完数据,ObjectInputStream.readObject 方法将抛出您看到的异常。

您预计流中有多少个对象,为什么要读完它们?

关于尝试执行 java 套接字操作时出现 java.io.EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7666997/

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