Read binary data from a socket

二次信任 提交于 2020-02-03 23:46:10

问题


I'm trying to connect to a server, and then send it a HTTP request (GET in this case). The idea is request a file and then receive it from the server.

It should work with both text files and binary files (imgs for example). I have no problem with text files, it works perfect, but I'm having some troubles with binary files.

First, I declare a BufferedReader (for reading header and textfile) and a DataInput Stream:

BufferedReader in_text = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));

DataInputStream in_binary = new DataInputStream(
    new BufferedInputStream(socket.getInputStream()));

Then, I read the header with in_text and discover if it's a textfile or binary file. In case it's a textfile, I read it correctly in a StringBuilder. In case it's a binary file, I declare a byte[filesize] and store the following content of in_binary.

byte[] bindata = new byte[filesize];
in_binary.readFully(bindata);

And it doesn't work. I get a EOFException.

I thought that maybe in_binary is still in the first position of the stream, so it hasn't read the header yet. So I captured the length of the header and skip that bytes in in_binary.

byte[] bindata = new byte[filesize];
in_binary.reset();
in_binary.skip(headersize);
in_binary.readFully(bindata);

And still the same.

What could be happening?

Thanks!

PD: I know I could use URLConnection and all of that. That's not the problem.


回答1:


BufferedReader buffers data (hence the name) - it will almost certainly have read more data from the socket than just the header. Therefore, when you try to read the actual data some has already been read from the socket. If you try reading just a few bytes you'll probably see that they aren't the first bytes of the actual response data.

If you know how to use URLConnection, I have to wonder what reason you have for not using it.




回答2:


As soon as you use any subclass of Reader, you aren't reading binary. You are converting from bytes to characters, using the default encoding of the JVM. If you really want bytes of binary, you need to stick to streams, not readers. Creating both stacks at once is asking for trouble.

Use Apache Commons IO: IOUtils.toByteArray() to read the entire content into memory as a byte[], and then decide what to do with it, unless you have a gigantic amount of data, in which case you should set up the buffered input stream, decide what to do, and only construct the reader after you push back.



来源:https://stackoverflow.com/questions/4117791/read-binary-data-from-a-socket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!