通过写两个小程序来实现两台电脑之前屏幕监控小功能
一、server端
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.net.ServerSocket;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ScreenRobot {
public static void main(String[] args) throws Exception {
//创建Robot对象来获取桌面截图
Robot robot = new Robot();
//截取分辨率
Rectangle rec = new Rectangle(1366,768);
//server监听端口 等待连接
ServerSocket ss = new ServerSocket(8888);
while(true){
try{
//连接成功获取socket
Socket so = ss.accept();
//截屏
BufferedImage bi = robot.createScreenCapture(rec);
//发送到输出端
ImageIO.write(bi, "jpeg", so.getOutputStream());
so.getOutputStream().flush();
so.getOutputStream().close();
so.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
二、请求端
import java.awt.image.BufferedImage;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ScreenPanel {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建显示frame
JFrame jf = new JFrame();
jf.setSize(1366, 768);
jf.setVisible(true);
while(true){
try{
//请求server端
Socket socket = new Socket("127.0.0.1",8888);
//获取图片
BufferedImage bi = ImageIO.read(socket.getInputStream());
JLabel lab = new JLabel();
jf.setContentPane(lab);
lab.setSize(1366, 768);
ImageIcon ii = new ImageIcon(bi);
//label展示从server端收到的图片
lab.setIcon(ii);
socket.close();
//休眠一小下,可自动调节
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
首选运行server端然后运行请求端就可以看到运行结果,大概下图的样子,
运行时候分开为两台电脑运行可一直观测到另一台电脑的操作