【问题标题】:ObjectOutputStream not sending dataObjectOutputStream 不发送数据
【发布时间】:2012-02-23 21:04:33
【问题描述】:

客户端代码:

try {
            Socket socket = new Socket(ip, port);
            OutputStream output = socket.getOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(output);
            InputStream input = socket.getInputStream();
            ObjectInputStream in = new ObjectInputStream(input);
            out.writeByte(1);
            FileHandler fh = (FileHandler) in.readObject();
            //processing stuff
            out.flush();
            out.close();
            output.flush();
            output.close();
            input.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

服务器代码:

        try {
            ServerSocket server = new ServerSocket(port);
            Socket socket = server.accept();
            InputStream input = socket.getInputStream();
            ObjectInputStream in = new ObjectInputStream(input);
            int type = in.readByte();
            //processing stuff (which includes closing the streams and sending FileHandler object)
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

服务器从不接收字节。它只是等待来自客户端的字节,它永远不会到来。我不确定为什么它没有发送或收到。非常感谢任何帮助。

【问题讨论】:

    标签: java sockets networking stream objectoutputstream


    【解决方案1】:

    如果我不得不猜测,那是因为在您的客户端中,您阻塞了 in.readObject();,等待服务器向您发送一些东西,因此永远不会刷新输出流,因此......什么都不会发送。

    在刷新输出流之后将读取移至

    【讨论】:

    • 也不要刷新或关闭输出。如果您包装一个调用 close 或 flush 或 close 的 OutputStream ,它将依次刷新包含的流。您不需要保存对输出或输入的引用。如果抛出异常,Close 也应该放在 finally 子句中,您仍然需要确保发生流的 close()。
    • 发送字节后刷新时,服务器收到连接重置错误。
    • @JonMannerberg - 不,当你 关闭 连接时它会得到它。在完成阅读和写作之前不要关闭它。
    【解决方案2】:

    尝试使用 writeObject 和 readObject 方法。还要将 Integer 而不是 int 写入流。在继续之前阅读this really good lecture

    This is also a good lecture 解决您的问题。

    问候!

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 2018-04-12
      • 2013-07-13
      • 2015-11-17
      相关资源
      最近更新 更多