Server端(用来接收远程主机的操作指令)
1、创建继承Remote接口的子接口,用来实现一些操作计算的方法
public interface RobotControlI extends Remote {
public BufferedImage createScreenCapture(Rectangle screenRect)
throws RemoteException;
// 获取远程主机屏幕指定坐标的像素颜色
public Color getPixelColor(int x, int y) throws RemoteException;
// 执行远程主机键盘指定按键的按下动作
public void keyPress(int keycode) throws RemoteException;
// 执行远程主机键盘指定按键的抬起动作
public void keyRelease(int keycode) throws RemoteException;
// 执行远程主机的鼠标移动方法
public void mouseMove(int x, int y) throws RemoteException;
// 执行远程主机的鼠标指定按键的按下动作
public void mousePress(int buttons) throws RemoteException;
// 执行远程主机的鼠标指定按键的释放动作
public void mouseRelease(int buttons) throws RemoteException;
// 执行远程主机的鼠标滚轮动作
public void mouseWheel(int wheelAmt) throws RemoteException;
}
2、创建一个导出远程对象的类,远程实现robot类的相关接口方法
public class RobotControlImpl extends Robot implements RobotControlI {
public RobotControlImpl() throws RemoteException, AWTException {
//使用提供的特定端口导出远程对象,以便能够接收传入的调用。
UnicastRemoteObject.exportObject(this, 0);
}
}
3、创建远程调用的存根(也就是服务器的代理对象,用于执行本地方法)
RobotControlImpl remoteRobot_Server = new RobotControlImpl();
4、启动RMI服务器(默认端口是1099)
Registry registry = LocateRegistry.createRegistry(1098);
5、注册RMI实现类
registry.rebind("robot", remoteRobot_Server);
Client端:
1、创建和服务端对应的实现接口类
public interface RobotControlI extends Remote {
public BufferedImage createScreenCapture(Rectangle screenRect)
throws RemoteException;
// 获取远程主机屏幕指定坐标的像素颜色
public Color getPixelColor(int x, int y) throws RemoteException;
// 执行远程主机键盘指定按键的按下动作
public void keyPress(int keycode) throws RemoteException;
// 执行远程主机键盘指定按键的抬起动作
public void keyRelease(int keycode) throws RemoteException;
// 执行远程主机的鼠标移动方法
public void mouseMove(int x, int y) throws RemoteException;
// 执行远程主机的鼠标指定按键的按下动作
public void mousePress(int buttons) throws RemoteException;
// 执行远程主机的鼠标指定按键的释放动作
public void mouseRelease(int buttons) throws RemoteException;
// 执行远程主机的鼠标滚轮动作
public void mouseWheel(int wheelAmt) throws RemoteException;
}
2、获取注册列表
Registry registry = LocateRegistry.getRegistry("服务端IP", 1098);
3、获取RMI实现类
private RobotControlI robot;
robot = (RobotControlI) registry.lookup("robot");
4、将Client的操作指令传给Server端,并在Server端执行
public void keyPressed(KeyEvent e) {
try {
robot.keyPress(e.getKeyCode());
} catch (RemoteException e1) {
e1.printStackTrace();
}
}