java socket远程屏幕监视(二)

服务端

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;

public class Server implements Runnable{
	private DataOutputStream out;
	private Robot robot;
	private ServerSocket ss;
	private BufferedImage image;
	public static void main(String[] args) {
		new Server();
	}

	public Server() {
		try {
			ss = new ServerSocket(9090);
			System.out.println("开始监听");
			Socket client = ss.accept();
			System.out.print("控制端连上");
			
			out = new DataOutputStream(client.getOutputStream());
			robot = new Robot();
			new Thread(this).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
		//Rectangle rec = new Rectangle(0, 0, (int) size.getWidth(),(int) size.getHeight());//捕获屏幕的区域
		Rectangle rec = new Rectangle(size);//捕获全屏
		try {
			while (true) {
				// 抓取一张屏幕图片
				image = robot.createScreenCapture(rec);
				ByteArrayOutputStream bout = new ByteArrayOutputStream();
				ImageIO.write(image, "jpeg", bout);//把图片放进bout

				byte[] b = bout.toByteArray();//把bout转成字节数组
				out.writeInt(b.length);//向客户端发送图片字节的长度
				out.write(b);//向客户端发送图片
				out.flush();
				Thread.sleep(100);//一秒传10张图片
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

客户端

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Client extends JFrame implements Runnable {

	private DataInputStream dins;
	private JLabel imageLab;

	public static void main(String[] args) {
		new Client();
	}

	public Client() {
		imageLab = new JLabel();
		this.add(imageLab);
		this.setSize(500, 500);
		this.setLocation(300, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		
		new Thread(this).start();//启动线程
	}

	public void run() {
		try {
			Socket socket = new Socket("192.168.0.102", 9090);
			dins = new DataInputStream(socket.getInputStream());
			while (true) {
				int imageLen = dins.readInt();//读取服务器发送过来的图片字节长度
				byte[] iData = new byte[imageLen];
				dins.readFully(iData);

				ByteArrayInputStream bins = new ByteArrayInputStream(iData);
				BufferedImage image = ImageIO.read(bins);//转成图片
				ImageIcon icon = new ImageIcon(image);
				imageLab.setIcon(icon);
				imageLab.repaint();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


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