本文實例講述了java透過控制滑鼠實現螢幕廣播的方法。分享給大家供大家參考。具體分析如下:
在前面一篇《java實現螢幕共享功能實例分析》中提到截取螢幕時是沒滑鼠,為了看到教師端介面上的滑鼠,可以在截取螢幕的時候,把滑鼠繪製到每一個截圖上去,但是由於截圖的時候是一張張截取的,所以看到的滑鼠難免會有點卡,之前寫了java滑鼠操控小程序,可以透過這種方式來看到滑鼠的示範。
實現的方式也挺簡單的,前面兩篇文章分別實現了滑鼠控制和沒有滑鼠的螢幕分享功能,把這兩個結合一下就ok了,下面簡單分析下。
服務端,將SendScreenImg和SendMouseMessage看作兩個工具類,分別監聽不同的端口,他們兩個都實現了Thread類,我們用線程池ExecutorService類控制他們。
使用了兩個端口,因為暫時還不知道該如何吧滑鼠資訊和圖片的資訊一起發送,或許可以把圖片轉換成字節數組的形式,把滑鼠的座標放在數組前面,不過這樣的話滑鼠可能也會不連貫,因為傳送滑鼠座標的速度會比傳圖片的快一些,嗯,有空再試試。
客戶端類比上面就是了。
下面是程式碼:
服務端:
主程式:
複製碼代碼如下:/*
* 螢幕廣播類,呼叫了兩個工具類:發送截圖訊息的類別和發送滑鼠的訊息類,利用了線程池。
*/
public class BroderCast {
public static void main(String[] args)
{
new BroderCast();
System.out.println("開始");
}
public BroderCast()
{
ExecutorService exector = Executors.newFixedThreadPool(2);
exector.execute(new SendScreenImg());
exector.execute(new SendMouseMessage());
}
}
發送截圖代碼:
複製程式碼如下:import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
/*
* 工具類:發送教師端截圖訊息給學生端,沒有滑鼠訊息,使用了8002號端口
* 可以在發送的圖片上面組件繪製滑鼠的訊息,從而實現在學生端介面上看到滑鼠訊息,暫未實現該功能
*
*/
public class SendScreenImg extends Thread
{
public int serverPort=8002;
private ServerSocket serverSocket;
private Robot robot;
public Dimension screen;
public Rectangle rect ;
private Socket socket;
public static void main(String args[])
{
new SendScreenImg().start();
}
public void changeServerPort(int serverPort)
{
if(this.serverPort == serverPort) return ;
try{
this.serverSocket.close(); //有必要先關閉目前連接埠
this.serverPort = serverPort;
serverSocket = new ServerSocket(this.serverPort);
serverSocket.setSoTimeout(8000000);
}catch(Exception e){}
}
//建構方法開啟套接字連接機器人robot 取得螢幕大小
public SendScreenImg()
{
try {
serverSocket = new ServerSocket(getServerPort());
serverSocket.setSoTimeout(864000000);
robot = new Robot();
} catch (Exception e) {
e.printStackTrace();
}
screen = Toolkit.getDefaultToolkit().getScreenSize(); //取得主畫面的大小
rect = new Rectangle(screen); //建構對應大小的矩形
}
@Override
public void run()
{
//即時等待接收截圖訊息
while(true){
try {
socket = serverSocket.accept();
ZipOutputStream zip = new ZipOutputStream(new DataOutputStream(socket.getOutputStream()));
zip.setLevel(9); //設定壓縮級別
try{
BufferedImage img = robot.createScreenCapture(rect);
zip.putNextEntry(new ZipEntry("test.jpg"));
ImageIO.write(img, "jpg", zip);
if(zip!=null)zip.close();
System.out.println("學生連接埠已經連接");
} catch (IOException ioe) {
System.out.println("被控端:disconnect");
}
} catch (IOException ioe) {
System.out.println("連線出錯");
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
}
發送滑鼠訊息:
複製碼代碼如下:/*
* 工具類別:取得滑鼠的資訊並且傳送給學生端
*/
public class SendMouseMessage extends Thread{
private int OPERATE_PORT = 8001;
private ServerSocket server;
private Socket socket;
private String operateStr;
public static void main(String[] args)
{
new SendMouseMessage().start();
}
public SendMouseMessage(){
try {
server = new ServerSocket(OPERATE_PORT);
//JOptionPane.showMessageDialog(null, "已經開始監聽");
} catch (IOException e1) {
e1.printStackTrace();
}
}
//多執行緒在無線的循環中監聽客戶端的
public void run()
{
while(true){
Point point = MouseInfo.getPointerInfo().getLocation(); //
operateStr ="Movemouse,"+point.x+","+point.y;
try {
socket = server.accept();
socket.setSoTimeout(1000000);
DataOutputStream output =new DataOutputStream(socket.getOutputStream());
output.write(operateStr.getBytes());
output.flush(); //刷行輸出流,並且使所有緩衝的輸出位元組寫出
output.close(); //關閉輸出流且釋放資源
System.out.println("INFO: "+operateStr);
} catch (IOException e) {
System.out.println("已經停止連線");
break; //斷開連線的時候就停止無線循環
}
}
}
}
客戶端:
主程式:
複製程式碼如下:import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.Tool.OperateMouse;
import com.Tool.ReceiveImages;
public class ReceiveBroderCast {
public ExecutorService exector;
public static String IP="202.216.60.9";
public static void main(String[] args)
{
new ReceiveBroderCast(IP);
}
public ReceiveBroderCast(String IP) {
exector = Executors.newFixedThreadPool(2);
exector.execute(new ReceiveImages(IP));
exector.execute(new OperateMouse(IP));
}
}
接收截圖代碼:
複製碼代碼如下:/*
* ly 2014-11-20
* 此類別用於接收教師端的螢幕訊息,不包括滑鼠
* 使用socket()
*/
public class ReceiveImages extends Thread{
public BorderInit frame ;
public Socket socket;
public String IP;
public static void main(String[] args){
new ReceiveImages("202.216.60.7").start();
}
public ReceiveImages(String IP)
{
frame=new BorderInit();
this.IP=IP;
}
public void run() {
while(frame.getFlag()){
System.out.println("已經連線"+(System.currentTimeMillis()/1000)%24%60+"秒");
try {
socket = new Socket(IP,8002);
DataInputStream ImgInput = new DataInputStream(socket.getInputStream());
ZipInputStream imgZip = new ZipInputStream(ImgInput);
Image img = null;
try{
imgZip.getNextEntry(); //到Zip檔案流的開始處
img = ImageIO.read(imgZip); //依照位元組讀取Zip圖片流裡面的圖片
frame.jlbImg.setIcon(new ImageIcon(img));
frame.validate();
}catch (IOException e) {e.printStackTrace();}
try{
imgZip.close();
} catch (IOException e) {
System.out.println("連線中斷");
}
try {
TimeUnit.MILLISECONDS.sleep(50);// 接收圖片間隔時間
} catch (InterruptedException ie) {
ie.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {}
}
}
}
}
class BorderInit extends JFrame
{
private static final long serialVersionUID = 1L;
public JLabel jlbImg;
private boolean flag;
public boolean getFlag(){
return this.flag;
}
public BorderInit()
{
this.flag=true;
this.jlbImg = new JLabel();
this.setTitle("遠端監控--IP:" + "--主題:" );
this.setSize(400, 400);
//this.setUndecorated(true);
//this.setAlwaysOnTop(true); //總是在最前面
this.add(jlbImg);
this.setLocationRelativeTo(null);
this.setExtendedState(Frame.MAXIMIZED_BOTH);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
this.validate();
//視窗關閉事件
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
flag=false;
BorderInit.this.dispose();
System.out.println("視窗關閉");
System.gc(); //垃圾回收
}
});
}
}
接收滑鼠資訊並控制滑鼠移動:
複製程式碼如下:import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import javax.swing.JOptionPane;
/*
* 學生端控制滑鼠和教師端一致
* 類別負責接收滑鼠的資訊並且用robot.mouseMove()函數控制滑鼠移動
*/
public class OperateMouse extends Thread{
public static void main(String[] args)
{
new OperateMouse("202.116.60.7").start();
}
private Socket socket;
public String IP;
private int OPERATE_PORT = 8001;
private Robot robot;
public OperateMouse(String IP)
{
this.IP = IP;
}
public void run() {
while(true){
try {
socket = new Socket(IP,OPERATE_PORT);
robot = new Robot();
//取得滑鼠移動的信息
DataInputStream dataIn = new DataInputStream(socket.getInputStream());
String info="";
int r;
while((r=dataIn.read()) != -1){
info +=""+(char)r; //把位元組數組中所有元素都變成字元型
}
dataIn.close();
System.out.println("資料流斷開"+info);
if(info!=null){
String s[] = info.trim().split(",");
if("Movemouse".equals(s[0].trim()));
{
if (s.length == 3) {
int x = Integer.parseInt(s[1].trim());
int y = Integer.parseInt(s[2].trim());
System.out.println("輸出滑鼠的資訊"+x+" "+ y);
robot.mouseMove(x, y);
}
}
}
} catch (IOException e) {
System.out.println("已斷線");
break;
} catch (AWTException e) {
e.printStackTrace();
}
}
}
}
希望本文所述對大家的Java程式設計有幫助。