【问题标题】:Socket Inputstream doesn't return -1 at the end of stream套接字输入流在流结束时不返回 -1
【发布时间】:2012-11-08 11:21:03
【问题描述】:

这是发生问题的代码sn-p:

public static byte[] copyLargeExt(InputStream input) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*8];
        int n = 0;
        while(-1 != (n = input.read(buffer))) {
            baos.write(buffer, 0, n);
        // i just append this pattern ({###END###}) to force the break  
           /*if(baos.toString(UTF8.name()).endsWith("{###END###}")) {
                break;
            }*/
        }
        return baos.toByteArray();
    }

有人可以帮我吗?

【问题讨论】:

  • 这样就永远循环了?您的输入流来自哪里?
  • 它只是不会永远循环,但它什么也不返回。输入流来自 Google(Postman)
  • 套接字关闭时将到达流的末尾。谁在关闭套接字?
  • 必须在写回输出流后才关闭套接字

标签: java sockets inputstream serversocket bytearrayoutputstream


【解决方案1】:

问题中的代码读取到套接字流的末尾。如果方法是阻塞的并且在read调用中,那只能说明另一端还没有关闭其对应的输出流。

你有两个选择:

  • 更改另一端以关闭其输出流,以便此代码看到 EOF。

  • 更改“协议”,以便此代码知道预期的数据字节数......并准确读取该字节数。

【讨论】:

    【解决方案2】:

    在 Java 中。
    如果服务器只有Socket.close(),没有OutputStream.close(),客户端的InputStream.read()不会返回-1
    相反,客户端的InputStream.read() 将阻塞直到超时。 所以服务器上的最佳实践是:

    OutputStream.close();
    InputStream.close();
    Socket.close();
    

    【讨论】:

    • 我想知道它在InputStream.close() 中的作用是什么?这是否会发送一个特殊字符来表示 EOF?
    猜你喜欢
    • 2014-01-06
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    相关资源
    最近更新 更多