java socket远程屏幕监视(一)

找的代码,整理了一下,发出来


在Eclipse中处理图片,需要引入两个包:
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
报错:
Access restriction: The type JPEGImageEncoder is not accessible due to restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar

此时解决办法:
Eclipse默认把这些受访问限制的API设成了ERROR。只要把

Windows-Preferences-Java-Complicer-Errors/Warnings里面的

Deprecated and restricted API中的Forbidden references(access rules)

选为Warning就可以编译通过。


服务端

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.*;
import com.sun.image.codec.jpeg.*;

public class Server implements Runnable {
	Dimension screenSize;
	Rectangle rectangle;
	Robot robot;//机器人
	Socket socket;
	ServerSocket ss;
	BufferedImage image;
	public static void main(String[] args) {
		new Server();
	}
	
	public Server() {
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		rectangle = new Rectangle(screenSize);// 可以指定捕获屏幕的区域
		
		try {
			robot = new Robot();
			ss = new ServerSocket(5000);
			System.out.println("服务器已经启动。。。。。");
			socket= ss.accept();// 获取一个SOCKET
			System.out.println("有客户端连接。。。。。");
			
			new Thread(this).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		JPEGImageEncoder encoder=null;
		try {
			encoder = JPEGCodec.createJPEGEncoder(socket.getOutputStream());
			while (true) {
				// 捕获制定屏幕矩形区域
				image = robot.createScreenCapture(rectangle);
				encoder.encode(image);//传送图片
				Thread.sleep(100);//图片采集时间
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}

客户端

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.Socket;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class Client extends JFrame {
	MyPanel mp;
	public static void main(String[] args) {
		new Client();
	}
	public Client() {
		mp=new MyPanel();
		this.add(mp);
		this.setSize(400, 400);// 窗口大小
		this.setLocation(200, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
}
class MyPanel extends JPanel implements Runnable {
	BufferedImage image = null;
	Socket socket = null;
	
	public MyPanel() {
		new Thread(this).start();
	}

	public void paint(Graphics g) {
		super.paint(g);
		g.drawImage(image, 0, 0, null);//画图片
	}
	
	public void run() {
		try {
			socket = new Socket("192.168.0.102", 5000);
			// 获得图像解码器
			JPEGImageDecoder de = JPEGCodec.createJPEGDecoder(socket.getInputStream());
			while (true) {
				image = de.decodeAsBufferedImage();// 从流中解码获得图像
				this.repaint();// 重画
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}


你可能感兴趣的:(java socket远程屏幕监视(一))