如何在java中识别InputStream的结尾 [英] How to identify end of InputStream in java

查看:150
本文介绍了如何在java中识别InputStream的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Socket程序从服务器读取字节,即我使用InputStream来读取字节。如果我传递长度大小,我能够读取字节,但我不确定长度是多少。所以我无法初始化字节数组。

I am trying to read bytes from server using Socket program, ie I am using InputStream to read the bytes. If I pass the length size I am able to read the bytes, but I am not sure what may be the length. So I am not able initialize the byte array.

我还尝试了 while(in.read()!= -1),我观察到它在发送数据时循环工作正常,但循环后的下一行不可执行,我觉得它仍然在寻找流中的数据,但没有数据。如果我关闭服务器连接,那么我的客户端将执行下一行,然后循环。

Also I tried while (in.read() != -1), I observered it loop works fine when the data is sent, but the next line after the loop is not executable, I feel its still looking for the data in the stream but there is no data. If I close the Server connection, then my client will execute the next line followed to the loop.

我不确定我哪里出错?

this.in = socket.getInputStream();

int dataInt = this.in.read();

while(dataInt != -1){
    System.out.print(","+i+"--"+dataInt);
    i++;
    dataInt = this.in.read();
}

System.out.print("End Of loop");

我得到的输出为: -

I get the output as:-

,1--0,2--62,3--96,4--131,5--142,6--1,7--133,8--2,9--16,10--48,11--56,12--1,13--0,14--14,15--128,16--0,17--0,18--0,19--48,20--0,21--0,22--0,23--0,24--0,25--1,26--0,27--0,28--38,29--114,30--23,31--20,32--70,33--3,34--20,35--1,36--133,37--48,38--51,39--49,40--52,41--49,42--55,43--49,44--52,45--52,46--54,47--55,48--50,49--51,50--52,51--48,52--53,53--56,54--51,55--48,56--48,57--57,58--57,59--57,60--57,61--57,62--57,63--57,64--56

但没有输出: -
结束循环

But no output for :- End Of loop

请指导我如何关闭循环?

Please guide how shall I close the loop?

期待您的回复。提前感谢你们。

Looking forward for you response. Thanking you all in advance.

推荐答案

它正在寻找更多数据,因为没有人告诉它不会是更多数据。网络的另一端可以随时发送更多数据。

It's looking for more data because nothing's told it that there won't be more data. The other end of the network could send more data at any time.

目前尚不清楚您是在设计客户端/服务器协议还是只是尝试实现它,但是通常有三种常见的方法来检测邮件的结尾:

It's not clear whether you're designing the client/server protocol or just trying to implement it, but typically there are three common ways of detecting the end of a message:


  • 关闭邮件末尾的连接

  • 将消息的长度放在数据本身之前

  • 使用分隔符;正常数据中永远不会出现的某些值(或者总是会以某种方式进行转义)

我个人赞成长度前缀(如果可能);它使阅读代码变得更加简单,但仍然允许同一连接上的多条消息。

Personally I favour length-prefixing when possible; it makes the reading code significantly simpler, but still allows multiple messages on the same connection.

(另外,我同意Daniel,你应该使用<$的重载c $ c>读取,它一次读取整个缓冲区而不是单个字节。这样效率会更高 - 但不会从根本上改变当前问题的性质。)

(Additionally, I agree with Daniel that you should be using the overload of read which reads a whole buffer at a time, instead of a single byte. This will be much more efficient - but doesn't fundamentally change the nature of your current issue.)

这篇关于如何在java中识别InputStream的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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