简体   繁体   中英

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!

I wouldn't use datagrams for this. If there are any network errors, congestion or the receiver cannot keep up, datagrams will be lost and your screenshots will be corrupted.

It is better to use a regular (eg TCP) socket, and let the transport layer deal with lost packets and recovery.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM