Java is a way to broadcast the screen by controlling the mouse

  • 2020-04-01 03:38:43
  • OfStack

This article illustrates how Java can broadcast a screen by controlling the mouse. Share with you for your reference. Specific analysis is as follows:

In the previous article "(link: #)" capture the screen is not mentioned in the mouse, in order to see the teacher on the backend interface of the mouse, you can at the time of capture screen, the mouse to draw up each a screenshot to, but because the screenshot is taken, so see the mouse will inevitably have a point card, written before the Java mouse manipulation of small procedures, can be in this way to see the mouse demo.

The way to achieve is also quite simple, the previous two articles respectively realized the mouse control and without the mouse screen sharing function, the two combined ok, the following simple analysis.

On the server side, think of SendScreenImg and SendMouseMessage as two utility classes that listen to different ports. Both of them implement the Thread class, which we control with the Thread pool ExecutorService class.

USES two ports, because don't know how to let the mouse yet information and pictures together to send, may be able to convert image to the form of a byte array, put the coordinates of the mouse in front of the array, so the mouse may be inconsistent, however, because of the speed of transmitting the mouse coordinates will be faster than the pictures, well, be free to try again.

The client analogy is above.

Here is the code:

Server:

The main program:

/*
 * The screen broadcast class, which calls two utility classes: the one that sends screenshots and the one that sends mouse messages, makes use of the thread pool.
 */
public class BroderCast {
    public  static void main(String[] args)
    {
        new BroderCast();
        System.out.println(" start ");
    }
    public BroderCast()
    {
        ExecutorService exector = Executors.newFixedThreadPool(2);
        exector.execute(new SendScreenImg());
        exector.execute(new SendMouseMessage());
    }
}

Send screenshot code:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
 
/*
 * Tool: send the teacher side screenshot information to the students side, there is no mouse information, used 8002 Port no.
 *      The mouse information can be drawn by the component above the picture sent, so that the mouse information can be seen on the student interface. This function has not been realized yet
 *             
 */
public  class SendScreenImg extends Thread
{
    public int serverPort=8002;
    private ServerSocket serverSocket;
    private Robot robot;
    public  Dimension screen;
    public Rectangle rect ;
    private Socket socket;
    public static void main(String args[])
    {
        new SendScreenImg().start();
    }
    
    public void changeServerPort(int serverPort)
    {
        if(this.serverPort == serverPort) return ;
        try{
            this.serverSocket.close();    //It is necessary to close the current port
            this.serverPort = serverPort;
            serverSocket = new ServerSocket(this.serverPort);
            serverSocket.setSoTimeout(8000000);
        }catch(Exception e){}
        
    }
    
    //Construction method & NBSP; Open socket connection & NBSP;         Robot robot    Gets screen size
    public SendScreenImg()
    {
        try {
            serverSocket = new ServerSocket(getServerPort());
            serverSocket.setSoTimeout(864000000);
            robot = new Robot();
        } catch (Exception e) {
            e.printStackTrace();
        }
        screen = Toolkit.getDefaultToolkit().getScreenSize();  //Gets the size of the home screen
        rect = new Rectangle(screen);                          //Construct a rectangle of corresponding size
        
    }
    @Override
    public void run()
    {
        //Wait in real time to receive screenshot message
        while(true){
            try {
                socket = serverSocket.accept();
                ZipOutputStream zip = new ZipOutputStream(new DataOutputStream(socket.getOutputStream()));
                zip.setLevel(9);     //Set the compression level
                try{
                    BufferedImage img = robot.createScreenCapture(rect);
                    zip.putNextEntry(new ZipEntry("test.jpg"));
                    ImageIO.write(img, "jpg", zip);
                    if(zip!=null)zip.close();
                    System.out.println(" The student port has been connected ");
                } catch (IOException ioe) {
                    System.out.println(" Accused of end: disconnect");
                }
            } catch (IOException ioe) {
             System.out.println(" Connection error ");
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }
}

Send mouse information:
/*
 * Tool class: gets the information of the mouse and sends it to the student side
 */
public class SendMouseMessage extends Thread{
    private int OPERATE_PORT = 8001;
    private ServerSocket server;
    private Socket socket;
    private String operateStr;
    public static void main(String[] args)
    {
        new SendMouseMessage().start();
    }
    public SendMouseMessage(){
        try {
            server = new ServerSocket(OPERATE_PORT);
            //JOptionPane. ShowMessageDialog (null, "has already begun to listen"); < br / >         } catch (IOException e1) {
            e1.printStackTrace();
        }      
    }
    //Multithreaded  
listen on the client in a wireless loop     public void run()
    {
        while(true){
            Point point = MouseInfo.getPointerInfo().getLocation();  //
            operateStr ="Movemouse,"+point.x+","+point.y;
            try {
                socket = server.accept();
                socket.setSoTimeout(1000000);
                DataOutputStream output =new DataOutputStream(socket.getOutputStream());
                output.write(operateStr.getBytes());
                output.flush();   //Brush the output stream and make all buffered output bytes write
                output.close();   //Close the output stream and release the resource
    
                System.out.println("INFO :   "+operateStr);
            } catch (IOException e) {
                System.out.println(" Connection stopped ");
                break;   //Stop the wireless loop when you disconnect             }
        }
    }
}

Client:

The main program:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import com.Tool.OperateMouse;
import com.Tool.ReceiveImages;
 
public class ReceiveBroderCast {
    public ExecutorService exector;
    public static String IP="202.216.60.9";
    
    public static void main(String[] args)
    {
        new ReceiveBroderCast(IP);
    }
    
    public ReceiveBroderCast(String IP) {
        exector = Executors.newFixedThreadPool(2);
        exector.execute(new ReceiveImages(IP));
        exector.execute(new OperateMouse(IP));
    }
}

Receiving screenshot code:
/*
 * ly  2014-11-20
 * This class is used to receive screen information on the teacher side, excluding the mouse
 * use socket()
 */
public  class ReceiveImages extends  Thread{
    public BorderInit frame ;
    public Socket socket;
    public String IP;
    
    public static void main(String[] args){
        new ReceiveImages("202.216.60.7").start();
    }
    public ReceiveImages(String IP)
    {
        frame=new BorderInit();
        this.IP=IP;
        
    }
    public void run() {
        while(frame.getFlag()){
            System.out.println(" Is connected "+(System.currentTimeMillis()/1000)%24%60+" seconds ");
            try {
                socket = new Socket(IP,8002);
                DataInputStream ImgInput = new DataInputStream(socket.getInputStream());
                ZipInputStream imgZip = new ZipInputStream(ImgInput);
                Image img = null;
                try{
                    imgZip.getNextEntry();   //To the beginning of the Zip file stream
                    img = ImageIO.read(imgZip); //
reads the images in the Zip image stream by byte                     frame.jlbImg.setIcon(new ImageIcon(img));
                    frame.validate();
                }catch (IOException e) {e.printStackTrace();}
                
                try{
                    imgZip.close();
                } catch (IOException e) {
                    System.out.println(" Connection is broken ");
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(50);//Time between receiving images
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }      
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    socket.close();
                } catch (IOException e) {} 
            }      
        }  
    }
}
class BorderInit extends JFrame
{
    private static final long serialVersionUID = 1L;
    public JLabel jlbImg;
    private boolean flag;
    public boolean getFlag(){
        return this.flag;
    }
    public BorderInit()
    {
        this.flag=true;
        this.jlbImg = new JLabel();
        this.setTitle(" Remote monitoring --IP:"  + "-- The theme :" );
        this.setSize(400, 400);
        //this.setUndecorated(true);
        //this.setAlwaysOnTop(true);  // Always at the front
        this.add(jlbImg);
        this.setLocationRelativeTo(null);
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);
        this.validate();
    
        //Window closing event
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                flag=false;
                BorderInit.this.dispose();
                System.out.println(" Form closed ");
                System.gc();    //Garbage collection
            }
        });
    }
}

Receive mouse information and control mouse movement:
import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
 
import javax.swing.JOptionPane;
 
/*
 * The students end    Control the mouse and the teacher end consistent
 * The class   Responsible for receiving information from the mouse   And use robot.mouseMove() Function controls mouse movement  
 */
public class OperateMouse extends Thread{
    public static void main(String[] args)
    {
        new OperateMouse("202.116.60.7").start();
    }
    private Socket socket;
    public String IP;
    private int OPERATE_PORT = 8001;
    private Robot robot;
    
    public OperateMouse(String IP)
    {
        this.IP = IP;
    }
    public void run() {
        while(true){
            try {
                socket = new Socket(IP,OPERATE_PORT);
                robot = new Robot();
                //Gets information about mouse movement
                DataInputStream dataIn = new DataInputStream(socket.getInputStream());       
                String info="";
                int r;
                while((r=dataIn.read()) != -1){
                    info +=""+(char)r;   //Converts all elements in the byte array to a character
                }
                dataIn.close();
                System.out.println(" Data stream disconnection "+info);
                if(info!=null){
                        String s[] = info.trim().split(",");
                        if("Movemouse".equals(s[0].trim()));
                        {
                            if (s.length == 3) {
                                int x = Integer.parseInt(s[1].trim());
                                int y = Integer.parseInt(s[2].trim());
                                System.out.println(" Output mouse information "+x+"  "+ y);
                                robot.mouseMove(x, y);
                            }
                        }
                    }
            } catch (IOException e) {
                System.out.println(" Disconnected connection ");
                break;
            } catch (AWTException e) {
                e.printStackTrace();
            }
        }
    }
}

I hope this article has been helpful to your Java programming.


Related articles: