1

Can anyone tell what wrong with this code, what I done is that

  1. Client send image data which is uchar array from c++.
  2. Java server receives this data using server socket and store as byte array.

Here is the code...

   private ServerSocket serverSocket;
   InputStream in;
   int imageSize=300;//921600;//expected image size 640X480X3
   public imageReciver(int port) throws IOException {
      serverSocket = new ServerSocket(port);
    }


        Socket server = null;
        server = serverSocket.accept();
        in = server.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buffer[] = new byte[100];

        int remainingBytes = imageSize; //
        while (remainingBytes > 0) {
        int bytesRead = in.read(buffer);
        if (bytesRead < 0) {
         throw new IOException("Unexpected end of data");
         }
        baos.write(buffer, 0, bytesRead);
        remainingBytes -= bytesRead;
        }
        in.close();

        byte imageByte[] = new byte[imageSize];         
        imageByte = baos.toByteArray();   
        baos.close();

While reading from inputstream in I am getting negative value on buffer.

Haris
  • 13,645
  • 12
  • 90
  • 121

2 Answers2

4

I think the problem is:

Java's byte is signed and you are sending unsigned bytes.

From Java docs:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

You can try something like:

short bVal = /*signed byte*/;
if (bVal < 0) 
   bVal = bVal + 256; //Convert to positive

Edit: As pointed out by @Aubin, a short will be a better choice instead of an int.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
0

The representation of a data as signed or unsigned is a human convention. This convention is used by the processor when arithmetic is used.

It's not the case here: it's simple read and write and the fact the bit 7 is used as negative flag or not as no effect.

Reading a socket and writing a file may be done with byte buffer or better with ByteBuffer. I suggest a buffer size of 8K.

Rewriting the code using java.nio.channels may be better.

Community
  • 1
  • 1
Aubin
  • 14,617
  • 9
  • 61
  • 84