Receive byte[] using ByteArrayInputStream from a socket

hkguile picture hkguile · May 7, 2012 · Viewed 43k times · Source

Here is the code but got error:

bin = new ByteArrayInputStream(socket.getInputStream());

Is it possible to receive byte[] using ByteArrayInputStream from a socket?

Answer

Ernest Friedman-Hill picture Ernest Friedman-Hill · May 7, 2012

No. You use ByteArrayInputStream when you have an array of bytes, and you want to read from the array as if it were a file. If you just want to read arrays of bytes from the socket, do this:

InputStream stream = socket.getInputStream();
byte[] data = new byte[100];
int count = stream.read(data);

The variable count will contain the number of bytes actually read, and the data will of course be in the array data.