最近在做一个软工的屏幕监控软件,已经实现了屏幕图片的传输,但是没有鼠标,才发现键盘上的PtrScSysRq键所截到图是没有鼠标信息的。==
暂时只需实现鼠标的移动事件,用robot.mouseMove(x,y)函数实现,所以就没有用到MouseEvent对象,用了MouseInfo类中的getPointerInfo()方法。
且需知道在Swing程序中,通常通过鼠标事件的MouseEvent对象,来获取鼠标的坐标,而这种情况只能在窗体事件中获取(参考Java通过MouseInfo获取鼠标位置)
程序分为控制端与被控制端,在两台pc上运行。
控制端
import java.awt.MouseInfo;
import java.awt.Point;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
//教师端把 鼠标的信息发给 学生端口
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; //断开连接的时候就停止无线循环
}
/\*try {
Thread.sleep(100);
System.out.println("停止100微秒");
} catch (InterruptedException e) {
e.printStackTrace();
}\*/
}
}
}
被控端
import java.awt.AWTException;
import java.awt.Robot;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
/*
* 学生端 控制鼠标和教师端一致
* 该类 负责接收鼠标的信息 并且用robot.mouseMove()函数控制鼠标移动
*/
public class OperateMouse implements Runnable{
public static void main(String[] args)
{
new Thread(new OperateMouse()).start();
}
private Socket socket;
private int OPERATE_PORT = 8001;
private Robot robot;
@Override
public void run() {
while(true){
try {
socket = new Socket("202.116.60.6",OPERATE\_PORT);
robot = new Robot();
DataInputStream dataIn = new DataInputStream(socket.getInputStream());
String info="";
int r;
while((r=dataIn.read()) != -1){
info +=""+(char)r; //把字节数组中所有元素都变为字符型
// System.out.println("当前读到的数据时"+info);
}
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章