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