Search code examples
javasocketsioinputstreambytearrayinputstream

Receive byte[] using ByteArrayInputStream from a socket


Here is the code but got error:

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

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


Solution

  • 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.