为什么使用 Java Sockets 永远不会到达输入流的末尾? [英] Why is the end of the input stream never reached using Java Sockets?

查看:27
本文介绍了为什么使用 Java Sockets 永远不会到达输入流的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个简单的代理.我无法将整个给定请求读入字节数组.具体来说,在下面的循环中,即使客户端已经发送了它会发送的所有数据(即永远不会到达流的末尾),对读取"的调用也会阻塞.因为在我读完整个输入之前我不能确定是时候开始写入输出,所以这会造成一些麻烦.如果我终止与服务器的连接,则最终到达流的末尾,并且一切顺利(来自客户端的所有数据,在本例中为 Firefox 请求 www.google.com,已被服务器读取,并且它能够根据需要处理它,但显然它不能将任何东西发送回客户端).

public static void copyStream(InputStream is, OutputStream os) 抛出 IOException{int 读 = 0;byte[] 缓冲区 = 新字节 [BUFFER_SIZE];while((read = is.read(buffer, 0, BUFFER_SIZE)) != -1){os.write(buffer, 0, read);}返回;}

InputStream 直接来自客户端套接字(getInputStream(),然后缓冲);OutputStream 是一个 ByteArrayOutputStream.

我做错了什么?

解决方案

通常在 HTTP 中,Content-Length 标头指示您应该从流中读取多少数据.基本上它会告诉您在表示 HTTP 标头结束的双换行符(实际上是双\r\n)后面有多少字节.请参阅 W3C 了解更多信息...>

如果没有发送 Content-Length 标头,您可以尝试在经过一定时间后没有通过连接发送数据的情况下中断读取,尽管这绝对不是可取的.

(我假设您将以某种方式处理正在读取的数据,否则您可以在读取时写出每个字节)

I am writing a simple proxy in Java. I am having trouble reading the entirety of a given request into a byte array. Specifically, in the following loop, the call to 'read' blocks even though the client has sent all the data that it will (that is, the end of stream is never reached). As I can't be sure that it is time to start writing output until I've read the entirety of the input, this is causing a bit of trouble. If I kill the connection to the server, the end of stream is finally reached, and everything goes off without a hitch (all of the data from the client, in this case Firefox requesting www.google.com, has been read by the server, and it is able to process it as required, though obviously it can't send anything back to the client).

public static void copyStream(InputStream is, OutputStream os) throws IOException
{
    int read = 0;
    byte[] buffer = new byte[BUFFER_SIZE];
    while((read = is.read(buffer, 0, BUFFER_SIZE)) != -1)
    {
      os.write(buffer, 0, read);
    }
    return;
}

The InputStream comes from the client socket (getInputStream(), then buffered) directly; the OutputStream is a ByteArrayOutputStream.

What am I doing wrong?

解决方案

Typically in HTTP the Content-Length header indicates how much data you're supposed to read from the stream. Basically it tells you how many bytes follow the double-newline (actually double-\r\n) that indicates the end of the HTTP headers. See W3C for more info...

If there is no Content-Length header sent, you could try interrupting the read after a certain amount of time passes with no data sent over the connection, although that's definitely not preferable.

(I'm assuming that you're going to be processing the data you're reading somehow, otherwise you could just write out each byte as you read it)

这篇关于为什么使用 Java Sockets 永远不会到达输入流的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆