javanetwork-programmingvideodatainputstreamdataoutputstream

Java Video Chat applicataion input output stream not working


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();
            }
        }

Solution

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