Java implementation of remote control technology complete source code sharing _java

Source: Internet
Author: User
Tags flush gety

Implementation of remote control technology in Java

Java-java.net with its own. and Java.awt.robot can be used to implement remote control of another computer over a network, including controlling the movement of the mouse on the remote computer and inputting the keyboard, and obtaining images of the remote computer screen in real time. This article will use concise language and the logic of the simple and easy to teach you how to master this technology.
First look at the effect chart:
Remote-end Computer interface:


Control-side Computer interface:


Control-Side input:


Remote-side input:

Start with a detailed introduction to remote control of the technical ideas.
First, the two computers are connected through a java.net socket.

One end opens a serversocket, then the other end is connected with a socket.

Server-side

You should set a serversocket and initialize the input and output streams that you need to use:

 public static void OpenServer () throws IOException, classnotfoundexception{
 System.out.println ("ServerStart ..... ");
 ServerSocket Server = new ServerSocket (7777);
 Socket = Server.accept ();
 System.out.println ("Connected ... \ n" +socket);
 OIS = new ObjectInputStream (Socket.getinputstream ());
 Oos=new ObjectOutputStream (Socket.getoutputstream ());
 }

Client Side
You should use the socket to connect to the server and initialize the input output stream:

public static void Startconnection (String ip,int Port) throws Unknownhostexception, IOException, awtexception{
 Socket = new Socket ("192.168.0.106", 7777);
 if (socket.isconnected ()) {
  System.out.println ("Socket connected ..." +socket);
 }
 OOS = new ObjectOutputStream (Socket.getoutputstream ());
 OIS = new ObjectInputStream (Socket.getinputstream ());


 }

So the two computers are linked together and can exchange data through streams (InputStream and OutputStream).

Then you can think about what information you need to exchange between two computers to achieve remote control. First, the control side needs to continuously provide the intercepted screen image to the control (which we will implement with Java.awt.robot), and then the mouse and the keyboard do the same thing according to the event (InputEvent) coming from the control side (implemented by robot). Then the control side, of course, must first receive the image from the controlled end and reflect it to a panel (pane), then listen to the keyboard mouse action on the computer and then to the host on the control side (we can implement it by setting up a listener listener on the panel pane)

One of the problems encountered here is that the images used for transmission are not serializable either by image or by BufferedImage. So in order to solve this problem, we need to encapsulate the image data into a class and implements the Serializable interface, so we can not transmit it with i/ostream.
The image classes are as follows:

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;

Import java.io.Serializable;
 public class message implements Serializable {private static final long serialversionuid = 1L;  Private String FileName;  File name private long filelength;  File length private byte[] filecontent;
  The contents of the file () {} public message (String filePath) throws ioexception{filename = new file (FilePath);
  This.filelength=file.length ();

  This.filename=file.getname ();
  FileInputStream FIS = new FileInputStream (FilePath);
  byte[] bytes = new byte[(int) filelength];
  Fis.read (bytes,0, (int) filelength);

 This.filecontent=bytes;

 Public String GetFileName () {return fileName;}
 public void Setfilename (String fileName) {this.filename = filename;}
 Public long Getfilelength () {return filelength;


 public void Setfilelength (long filelength) {this.filelength = Filelength;} Public byte[] Getfilecontent () {returnFilecontent;}


public void Setfilecontent (byte[] filecontent) {this.filecontent = filecontent;}

 }

This enables the image to propagate through ObjectInputStream and ObjectOutputStream serialization.

After understanding the above basics, first we have to complete the UI settings of the control side, picture reception, and keyboard mouse action monitoring:

The first is to set the receive picture:

public static void Reveivepic () throws ClassNotFoundException, ioexception{message g = (message) ois.readobject ();
 FileOutputStream FOS = new FileOutputStream ("d:\\out\\" +g.getfilename ());
 Fos.write (g.getfilecontent (), 0, (int) g.getfilelength ());

 Fos.flush ();
 FileInputStream fis= New FileInputStream ("d:\\out\\" +g.getfilename ());
 BufferedImage BI = Imageio.read (FIS);

 Iic=new ImageIcon (BI);
 Image img = iic.getimage ();
  Toolkit tk = Toolkit.getdefaulttoolkit ();

  Dimension d =tk.getscreensize ();
  int w = d.width;
  int h =d.height;


  BufferedImage bi = resize (img,800,600);
  Imag_lab.seticon (New ImageIcon (BI)); Imag_lab.repaint ()//PIN off previously painted background} private static BufferedImage resize (Image img, int neww, int newh) {int w = IMG.GETW
  Idth (NULL);
  int h = img.getheight (null);
  BufferedImage dimg = new BufferedImage (NEWW, NEWH,BUFFEREDIMAGE.TYPE_INT_BGR);
  Graphics2D g = dimg.creategraphics (); G.setrenderinghint (Renderinghints.key_interpolation, Renderinghints.value_intErpolation_bilinear);
  G.drawimage (IMG, 0, 0, NEWW, NEWH, 0, 0, W, h, NULL);
  G.dispose ();
 return dimg;

 }

After receiving the message class from ObjectInputStream, you can reset the picture to the size of the panel pane and show it.

The next step is to set panel properties and listeners:

public static void ShowUI () {
 //console title
  JFrame JF = new JFrame ("console"); Setlistener (JF)
  ; Console size
  jf.setsize (+);
  Imag_lab is used to store the picture
  Imag_lab = new JLabel ();
  Jf.add (Imag_lab);
  Sets the console visible
  jf.setvisible (true);
  Console
  Jf.setalwaysontop (true);
  Jf.setresizable (true);
  Jf.setdefaultcloseoperation (Jframe.exit_on_close);


 }

Listener:

 public static void Setlistener (JFrame frame) {//panel Set listener Frame.addkeylistener (new Keyadapter () {public void ke
   ypressed (KeyEvent e) {sendeventobject (e);
   @Override public void keyreleased (KeyEvent e) {sendeventobject (e);
  @Override public void keytyped (KeyEvent e) {}}); Frame.addmousewheellistener (New Mousewheellistener () {public void mousewheelmoved (Mousewheelevent e) {SENDEVENTOBJ 
   ECT (e);
  }
  }); Frame.addmousemotionlistener (New Mousemotionlistener () {public void mousedragged (MouseEvent e) {sendeventobject (
   e);

   public void mousemoved (MouseEvent e) {sendeventobject (e);
  }
  });

   Frame.addmouselistener (New MouseListener () {public void mouseclicked (MouseEvent e) {sendeventobject (e);
   public void mouseentered (MouseEvent e) {sendeventobject (e);
   public void mouseexited (MouseEvent e) {sendeventobject (e); } public void mousepressed (MouseEvent e) {sendeventObject (e);
   public void mousereleased (MouseEvent e) {sendeventobject (e);
 }

  });
  private static void Sendeventobject (InputEvent event) {try{System.out.println ("send");
  Oos.writeobject (event);

  Oos.flush ();
  }catch (Exception EF) {ef.printstacktrace ();

 }

This completes the control end.

Next we will build the controlled side:
the controlled side needs to use robot to capture and send, and write a method to butt the received inputevent to react
The first is screenshots and sending:

 public static void Capturepic () throws Awtexception, ioexception{
 robot= new Robot ();
 Message msg = NULL;
 Toolkit tk = Java.awt.Toolkit.getDefaultToolkit ();
 Java.awt.Dimension DM =tk.getscreensize ();
 Java.awt.Robot Robot = new Java.awt.Robot ();
  for (int i = 0; i < i++) {
  //intercept the screen area of the specified size
  Rectangle rec = new Rectangle (0, 0, (int) dm.getwidth (), (int) dm< C9/>.getheight ());
  BufferedImage bimage = Robot.createscreencapture (rec);
  Save a picture to a file
  String FilePath = "D:\\out\\screenshot" +i+ ". jpeg";
  FileOutputStream fops =new FileOutputStream (filePath);
  Javax.imageio.ImageIO.write (bimage, "JPEG", fops);
  Fops.flush ();
  Fops.close ();
  MSG =new message (filePath);

  System.out.println (Msg.getfilename ());
  SYSTEM.OUT.PRINTLN ("send");
  Oos.writeobject (msg);
  Oos.flush ();

  }
 

Note that this code uses the D:\OUT\ directory as a storage place for temporary files, and readers use this code to set up their own temporary document storage

The robot is then implemented to operate on the received InputEvent instructions:

 public void action () throws Awtexception, ClassNotFoundException, ioexception{Robot robot= new Robot ();
  while (true) {inputevent E = (inputevent) ois.readobject ();
 if (e!=null) {handleevents (robot,e);} } public static void Handleevents (Robot action,inputevent event) {MouseEvent mevent = null;//mouse event Mousewheeleven T mwevent = null;//mouse scrolling event keyevent kevent = null; Keyboard event int mousebuttonmask =-100;
  mouse button switch (Event.getid ()) {case mouseevent.mouse_moved://mouse Mobile Mevent = (mouseevent) event;
  Action.mousemove (Mevent.getx (), mevent.gety ());
 break;
  Case mouseevent.mouse_pressed://mouse button Press Mevent = (mouseevent) event;
  Action.mousemove (Mevent.getx (), mevent.gety ());
  Mousebuttonmask = Getmouseclick (Mevent.getbutton ());
  if (mousebuttonmask!= -100) action.mousepress (mousebuttonmask);
  Break
  Case mouseevent.mouse_released://mouse button Release mevent = (mouseevent) event;
  Action.mousemove (Mevent.getx (), mevent.gety ()); Mousebuttonmask = Getmouseclick (Mevent.getbutton ())//Get mouse button if (mousebuttonmask!= -100) action.mouserelease (mousebuttonmask);
 break;
  Case Mouseevent.mouse_wheel://mouse scrolling mwevent = (mousewheelevent) event;
  Action.mousewheel (Mwevent.getwheelrotation ());
  break;
  Case mouseevent.mouse_dragged://Mouse dragging mevent = (mouseevent) event;
  Action.mousemove (Mevent.getx (), mevent.gety ());
  break;
  Case keyevent.key_pressed://Button kevent = (keyevent) event;
  Action.keypress (Kevent.getkeycode ());
  break;
  Case keyevent.key_released://Pine Key kevent= (keyevent) event;
  Action.keyrelease (Kevent.getkeycode ());
 break;


 Default:break; } private static int getmouseclick (int button) {//Get mouse button if (Button = mouseevent.button1)//left, Middle key for BUTTON2 re
 Turn inputevent.button1_mask;
 if (Button = = Mouseevent.button3)//Right key return inputevent.button3_mask;
 return-100; 

 }

The whole program is here to come to an end. The above program does not implement the encapsulation of the machine human thread. Complete the code can be used in the following site resources to download my resources: Http://xiazai.jb51.net/201608/yuanma/Java-RomoteControl (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.