简体   繁体   English

Java中的BufferedReader和套接字

[英]BufferedReader and Sockets in java

Suppose I'm using a Socket InputStream like this,in order to read the following data: 假设我正在使用这样的Socket InputStream,以便读取以下数据:
(first part encoded in ASCII) (第一部分以ASCII编码)

    the rest of this message is binaryCRLF  
    01100110010...

code: 码:

InputStreamReader isr = new InputStreamReader(socket.getInputStream()); 
BufferedReader in = new BufferedReader(isr);
String line = in.readLine();

what I expect at this point,is that line contains the text: 我现在期望的是该line包含以下文本:

the rest of this message is binary 此消息的其余部分为二进制

Then I would like to use the original socket InputStream: 然后,我想使用原始的套接字InputStream:

 InputStream is = socket.getInputStream();  
    ...

to read the binary part of the message. 读取消息的二进制部分。

Now, what if the BufferedReader has buffered some of the binary data, 现在,如果BufferedReader已经缓冲了一些二进制数据,
this would be a problem because I would miss part of the data. 这将是一个问题,因为我会丢失部分数据。
Am I misssing something ? 我想念什么吗?

In the source of BufferedReader you will see that the default buffer size is 8192. Because of this the call of readLine() will read more than the bytes of the first line into the buffer. BufferedReader的源代码中,您将看到默认的缓冲区大小为8192。因此,对readLine()的调用将读取多于第一行字节的缓冲区。

Use a different approach. 使用不同的方法。 Buffer the input and read it twice. 缓冲输入并读取两次。

try 尝试


InputStreamReader isr = new InputStreamReader(socket.getInputStream()); 
BufferedReader in = new BufferedReader(isr);
String line ="";
String buffer="";
while((buffer= in.readLine()) != null){ 
  line.concat(buffer); 
}

this way, till you have data in the BufferedReader, you would read it into line and would not loose any buffered data. 这样,直到在BufferedReader中有数据,您才可以将其读入行中,并且不会丢失任何缓冲的数据。 Cheers.. :) 干杯.. :)


Also for faster IO, use nio(New Input Output) libraries, especially ByteBuffer objects, where you can also flush the data from the stream using flush(). 同样,为了获得更快的IO,请使用nio(新输入输出)库,尤其是ByteBuffer对象,您还可以在其中使用flush()从流中刷新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM