【问题标题】:Java ObjectInputStream java.io.EOFExceptionJava ObjectInputStream java.io.EOFException
【发布时间】:2015-07-27 19:19:59
【问题描述】:

我正在尝试使用套接字将数据从MySQL 传递给客户端。对于List,我更喜欢使用数组,但如果我使用这个发送数组:

InputStream input = client.getInputStream();
        OutputStream output = client.getOutputStream();
        ObjectOutputStream obOutput = new ObjectOutputStream(output);
        Statement statement = dataConnection.createStatement();
        ResultSet modList = statement.executeQuery("SELECT modID, downloads FROM modRegister");
        String[][] mods = new String[3][3];
        int column = 0;
        while (modList.next()) {
            mods[column][1] = modList.getString("modID");
            mods[column][2] = modList.getString("downloads");
            ++column;
        }

        System.out.println(mods[1][1]);

        PrintWriter printClient = new PrintWriter(output);
        printClient.println(column);
        printClient.close();
        obOutput.writeObject(mods);
        obOutput.flush();

并使用以下方法从客户端接收它:

Socket server = new Socket("localhost", 25566);
    InputStream input = server.getInputStream();
    OutputStream output = server.getOutputStream();
    ObjectInputStream obInput = new ObjectInputStream(input);
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String s;
    int columns = 0;
    while((s = reader.readLine()) != null) {
        columns = Integer.parseInt(s);
        System.out.println(s);
    }
    String [][] mods;
    TimeUnit.SECONDS.sleep(10);
    mods = (String[][])obInput.readObject();

我收到了EOFException,即使有时间延迟。数组有效。我测试了打印出其中的所有数据。这是一个例外:

Caused by: java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at layout.MainStoreController.initialize(MainStoreController.java:36)
... 32 more

【问题讨论】:

  • 你能把layout.MainStoreController.initialize的代码贴出来吗?您发布的代码在堆栈中的哪个位置执行?
  • 嗯,其实就是第二个代码,在这个方法中仅此而已。
  • 你能发布整个方法定义吗?括号、名称、参数、类名和类路径?
  • 就是public void initialize(){theStuff above},包含了抛出异常,JavaFX的基本初始化方法

标签: java mysql sockets inputstream eofexception


【解决方案1】:

我怀疑关闭 PrintWriter 会关闭它写入的 OutputStream。

PrintWriter printClient = new PrintWriter(output);
printClient.println(column);
printClient.close();

当流关闭时,套接字也随之关闭,另一端在读取时会观察 End-Of-File。

【讨论】:

  • 确定吗?我在服务器中没有收到任何错误,所以我认为它正在发送它
  • 您可以使用wireshark捕获流量并查看实际发送的内容。我相信你会在那里看到一个关闭连接的 FIN 数据包。
  • 不,用flush替换了关闭以防止这种情况,仍然是同样的错误,而且很糟糕,我使用的是Windows,它实际上不支持带有Wireshark的localhost,不想编译一切都只是为了在我的 Ubuntu 服务器上尝试。
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
相关资源
最近更新 更多