原理:通过Robot截图,压缩成jpg格式,然后通过websocket发送给前端。
前端显示图像,发送鼠标事件,实现对远程电脑的控制。
再某些情况下,可以用来实现远程控制,目前只是一个雏形。
后端核心代码
@Component
public class ScreenCapture {
Robot robot ;//采集屏幕
Rectangle screenRectangle;//屏幕区域
public BufferedImage doCapture()
{
if(robot==null)this.init();
BufferedImage image = robot.createScreenCapture(screenRectangle); //采集图像
return image;
}
public void click(int x,int y) {
if(robot==null)this.init();
try {
robot.mouseMove(x, y);//移动到目标点
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);//点击
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);//松开
}
catch (Exception e) {
// TODO: handle exception
}
}
//初始化
private void init()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
screenRectangle = new Rectangle(screenSize);//采集区域
try {
robot = new Robot();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
@Component
public class CaptureThread {
private static final Logger LOG = LoggerFactory.getLogger(CaptureThread.class);
@Autowired
ScreenCapture screenCapture;//图片采集对象
Thread thread;
boolean isrun;
public void start() {
stop();
ClientService.screenCapture=screenCapture;//存储采集对象
thread=new Thread(task);
thread.start();
isrun=true;
}
public void stop() {
if(thread!=null) {
thread.interrupt();
}
isrun=false;
}
Runnable task=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (isrun) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();//内存文件
BufferedImage img=screenCapture.doCapture();//采集图像
ImageIO.write(img, "jpg", baos);//写入内存文件
ByteBuffer data=ByteBuffer.wrap(baos.toByteArray());//数据准备
ClientService.sendDataALL(data);//发送到页面
Thread.sleep(100);//休息一下
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
};
}
由于springboot默认将headless设置为true,因此启动的时候需要特别设置headless为false
headless意思就是不需要桌面相关功能,这个项目用到了桌面,所以要设置一下
//启动的时候必须吧headless设置为false
SpringApplicationBuilder builder=new SpringApplicationBuilder(ScreenApp.class);
builder.headless(false).run(args);
前端代码,比较简单,创建websocket,然后收图片,发控制数据
*{padding:0;margin:0;}
img{ width:100%; height:100%;}



