1

I am making a video chat app which uses java networking (aka. sockets) to send images of the webcam to another client.

My code sends first the length of the buffered image data then the actual data. The Server also reads first a int then the data itself. The first image worked but after it, the data input stream read a negative number as the length.

Server side:

frame = new JFrame();
        while (true) {
            try {

                length = input.readInt();
                System.out.println(length);
                imgbytes = new byte[length];
                input.read(imgbytes);
                imginput = new ByteArrayInputStream(imgbytes);
                img = ImageIO.read(imginput);
                frame.getContentPane().add(new JLabel(new ImageIcon(img)));
                frame.pack();
                frame.setVisible(true);

            }
            catch(IOException e){
            e.printStackTrace();
            }
        }

Client side:

while(true) {
            try {

                    currentimg = webcam.getImage();
                    ImageIO.write(currentimg, "jpg", imgoutputstream);
                    imgbytes = imgoutputstream.toByteArray();
                    out.writeInt(imgbytes.length);
                    out.write(imgbytes);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Clement
  • 128
  • 11
  • You are running into an infinite loop without a breaking condition at the client side. What will make you break from the inner while loop to read a new image from the webcam inside the outer loop? – Islam Hassan Mar 23 '19 at 08:17
  • I corrected the error but still it doesn't work. I added a debug `System.out.println()` in the Server side to print the length and here is the output `4465 8917 13388 17869 22323 26786 31233 35694 40168 44637 49116 53596 58062 62546 67038 -657982985 Exception in thread "main" java.lang.NegativeArraySizeException at ServerSide.ServerWorker.run(ServerWorker.java:39) at ServerSide.Server.(Server.java:42) at ServerSide.ServerMain.main(ServerMain.java:7)` – Clement Mar 23 '19 at 08:21

1 Answers1

2

On client side you always write the new image to the existing stream. That leads to an increasing array size in every iteration. In java int has a maximum of 2147483647. If you increase this integer it skips to the minimum value auf int which is negative (see this article).

So to fix this error you need to clear your stream before writing the next image so the size is never greater than integer's max value.

embie27
  • 96
  • 5