Search code examples
javastreamingudpdesktopdatagram

Send Desktop stream via datagram in Java


I want to capture the stream desktop and send it (to a client) via datagrams in Java. The following example makes a screenshot.

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class Captura{
    static public void captureScreen(String fileName) throws Exception {
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(fileName));
    }
//----
    public static void main(String[] args) {
        try{
            System.out.println("[ Captura iniciada ]");
            //sleep 5 sg
            Thread.currentThread().sleep(5*1000);
            String FILENAME="/home/jose/Desktop/captura01.png";
            Captura.captureScreen(FILENAME);
            System.out.println("[ Captura finalizada ]");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Do I have to use the Robot class too?, How I can send the stream?

Thank's for help.

Regards!


Solution

  • You can read in the just written screen shot file via an FileInputStream or you could directly write the image into a ByteArrayOutputStream:

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ImageIO.write(image, "png", buffer);
        byte[] data = buffer.toByteArray();
    

    Afterwards you can split the data into several packets and send them through a DatagramSocket (for one UDP package it will be too large).