0

My program takes a picture of the users screen, when they are using my program, to make a screenshot, then sends it to a server. The image will load about 1/4 of the way and freeze.

Sending the screenshot:

            BufferedImage buffimg = robot.createScreenCapture(captureSize);
            BufferedImage image = buffimg;
            byte[] imageInByte;


            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            imageInByte = baos.toByteArray();
            baos.close();

            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            out.println("!SCREENDATA!");
            out.flush();
            dos.writeInt(baos.toByteArray().length);
            dos.write(baos.toByteArray());
            dos.flush();

Getting the image:

                    if (input.startsWith("!SCREENDATA!")) {
                        System.out.println("reading");

                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        int len = dis.readInt();
                        System.out.println(len);
                        byte[] data = new byte[len];

                        dis.read(data);
                        InputStream in = new ByteArrayInputStream(data);
                        Image image = Toolkit.getDefaultToolkit().createImage(data);

                        v.repaint(image);
                    }

Displaying the image:

public void repaint(Image img) {

    frame.getContentPane().add(new JLabel(new ImageIcon(img)));
    frame.repaint();
    frame.pack();

}

If anyone could help me with this, I would appreciate it a lot!

1 Answers1

1

You need to keep calling dis.read(data); as this method on a TCP socket isn't designed to offer the entire buffer in one call (it's a stream socket, it keeps going). But be aware that the method call will block when the socket has no data to give. Also, it's best to send the file size in advance of the file so the other end knows how much to expect - it is less prone to protocol errors that can cause an infinite loop.

Have a look at the answers at how to achieve transfer file between client and server using java socket.

Anyway, an analogy: the socket has a bucket which fills up which is 512kb, let's say. You have a bucket that is 2048kb. You have to keep pouring the socket bucket into your own bucket.

Also, don't do stuff with Swing unless its on the Event Dispatch Thread. See How do you use the Event Dispatch Thread? for more details.

Community
  • 1
  • 1
Chris Dennett
  • 22,412
  • 8
  • 58
  • 84