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

时间:2011-10-05 19:59:31

标签: java sockets serialization

我在下面的代码中遇到以下异常。 当排除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)

Class ServerHandler:

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


 }

1 个答案:

答案 0 :(得分:5)

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

您期望在流中有多少个对象,为什么要阅读它们的结尾?