Java远程控制案例

wen java案例 1

本文目录导读:

Java远程控制案例

  1. 项目结构
  2. 服务器端(被控端)
  3. 客户端(控制端)
  4. 增强功能示例
  5. 使用说明
  6. 安全注意事项

我来为您提供一个完整的Java远程控制案例,包括服务器端(被控端)和客户端(控制端)的完整实现。

项目结构

remote-control/
├── src/
│   ├── server/
│   │   ├── RemoteServer.java
│   │   ├── ScreenCapture.java
│   │   └── CommandExecutor.java
│   └── client/
│       ├── RemoteClient.java
│       └── ScreenViewer.java

服务器端(被控端)

RemoteServer.java - 主服务器类

package server;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.util.concurrent.*;
public class RemoteServer {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private boolean running = true;
    private final int PORT = 5000;
    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("远程控制服务器已启动,等待连接...");
            System.out.println("服务器IP: " + InetAddress.getLocalHost().getHostAddress());
            while (running) {
                clientSocket = serverSocket.accept();
                System.out.println("客户端已连接: " + clientSocket.getInetAddress());
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void handleClient(Socket socket) {
        // 使用线程池处理客户端请求
        ExecutorService executor = Executors.newFixedThreadPool(2);
        // 屏幕捕获线程
        executor.submit(() -> {
            try {
                sendScreen(socket);
            } catch (Exception e) {
                System.err.println("屏幕传输错误: " + e.getMessage());
            }
        });
        // 命令接收线程
        executor.submit(() -> {
            try {
                receiveCommands(socket);
            } catch (Exception e) {
                System.err.println("命令接收错误: " + e.getMessage());
            }
        });
    }
    private void sendScreen(Socket socket) {
        try {
            OutputStream os = socket.getOutputStream();
            Robot robot = new Robot();
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            while (running && !socket.isClosed()) {
                try {
                    BufferedImage image = robot.createScreenCapture(screenRect);
                    // 压缩图片以提高传输效率
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(image, "jpg", baos);
                    byte[] imageBytes = baos.toByteArray();
                    // 发送图片大小和图片数据
                    DataOutputStream dos = new DataOutputStream(os);
                    dos.writeInt(imageBytes.length);
                    dos.write(imageBytes);
                    dos.flush();
                    // 控制传输频率
                    Thread.sleep(100); // 10fps
                } catch (Exception e) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void receiveCommands(Socket socket) {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (running && !socket.isClosed()) {
                String command = dis.readUTF();
                System.out.println("收到命令: " + command);
                // 执行命令
                if (command.startsWith("SHELL:")) {
                    CommandExecutor.execute(command.substring(6));
                } else if (command.startsWith("MOUSE:")) {
                    handleMouseCommand(command.substring(6));
                } else if (command.startsWith("KEY:")) {
                    handleKeyCommand(command.substring(4));
                } else if (command.equals("SHUTDOWN")) {
                    shutdown();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void handleMouseCommand(String command) {
        try {
            Robot robot = new Robot();
            String[] parts = command.split(",");
            if (parts[0].equals("CLICK")) {
                robot.mousePress(InputEvent.BUTTON1_MASK);
                robot.mouseRelease(InputEvent.BUTTON1_MASK);
            } else if (parts[0].equals("MOVE")) {
                int x = Integer.parseInt(parts[1]);
                int y = Integer.parseInt(parts[2]);
                robot.mouseMove(x, y);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void handleKeyCommand(String command) {
        try {
            Robot robot = new Robot();
            if (command.equals("ENTER")) {
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
            }
            // 可以扩展其他键盘操作
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void shutdown() {
        running = false;
        try {
            if (clientSocket != null) clientSocket.close();
            if (serverSocket != null) serverSocket.close();
            System.out.println("服务器已关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new RemoteServer().start();
    }
}

CommandExecutor.java - 命令执行器

package server;
import java.io.*;
import java.util.Scanner;
public class CommandExecutor {
    public static void execute(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            // 读取命令输出
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
                System.out.println("命令输出: " + line);
            }
            process.waitFor();
        } catch (Exception e) {
            System.err.println("命令执行错误: " + e.getMessage());
        }
    }
}

客户端(控制端)

RemoteClient.java - 客户端主类

package client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class RemoteClient extends JFrame {
    private Socket socket;
    private DataOutputStream dos;
    private ScreenViewer screenViewer;
    private JTextField ipField;
    private JButton connectButton;
    private JLabel statusLabel;
    public RemoteClient() {
        initUI();
    }
    private void initUI() {
        setTitle("远程控制客户端");
        setSize(1200, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 顶部控制面板
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new BorderLayout());
        // 连接设置面板
        JPanel connectionPanel = new JPanel(new FlowLayout());
        connectionPanel.add(new JLabel("服务器IP:"));
        ipField = new JTextField("localhost", 15);
        connectionPanel.add(ipField);
        connectButton = new JButton("连接");
        connectButton.addActionListener(e -> connectToServer());
        connectionPanel.add(connectButton);
        // 命令输入面板
        JPanel commandPanel = new JPanel();
        commandPanel.setLayout(new BorderLayout());
        JTextField commandField = new JTextField();
        commandField.addActionListener(e -> {
            if (socket != null && socket.isConnected()) {
                sendCommand("SHELL:" + commandField.getText());
                commandField.setText("");
            }
        });
        commandPanel.add(new JLabel("命令:"), BorderLayout.WEST);
        commandPanel.add(commandField, BorderLayout.CENTER);
        statusLabel = new JLabel("未连接");
        statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
        controlPanel.add(connectionPanel, BorderLayout.NORTH);
        controlPanel.add(commandPanel, BorderLayout.CENTER);
        controlPanel.add(statusLabel, BorderLayout.SOUTH);
        add(controlPanel, BorderLayout.NORTH);
        // 屏幕显示区域
        screenViewer = new ScreenViewer();
        add(screenViewer, BorderLayout.CENTER);
    }
    private void connectToServer() {
        try {
            String serverIP = ipField.getText();
            socket = new Socket(serverIP, 5000);
            dos = new DataOutputStream(socket.getOutputStream());
            statusLabel.setText("已连接: " + serverIP);
            connectButton.setText("已连接");
            connectButton.setEnabled(false);
            // 启动屏幕接收线程
            new Thread(() -> receiveScreen()).start();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, 
                "连接失败: " + ex.getMessage(), 
                "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    private void receiveScreen() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            while (socket != null && !socket.isClosed()) {
                int size = dis.readInt();
                byte[] imageBytes = new byte[size];
                dis.readFully(imageBytes);
                ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
                Image image = Toolkit.getDefaultToolkit().createImage(imageBytes);
                SwingUtilities.invokeLater(() -> {
                    screenViewer.updateImage(image);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void sendCommand(String command) {
        try {
            if (dos != null) {
                dos.writeUTF(command);
                dos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new RemoteClient().setVisible(true);
        });
    }
}

ScreenViewer.java - 屏幕显示器

package client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ScreenViewer extends JPanel {
    private Image currentImage;
    private boolean mouseClick = false;
    public ScreenViewer() {
        setBackground(Color.DARK_GRAY);
        // 鼠标事件处理
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                mouseClick = true;
            }
            @Override
            public void mouseReleased(MouseEvent e) {
                mouseClick = false;
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                // 发送鼠标位置
                sendMousePosition(e.getX(), e.getY());
            }
        });
    }
    private void sendMousePosition(int x, int y) {
        // 通过回调通知客户端发送鼠标位置
        // 简单起见,这里只做演示
        System.out.println("鼠标位置: " + x + ", " + y);
    }
    public void updateImage(Image image) {
        this.currentImage = image;
        repaint();
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (currentImage != null) {
            // 保持比例缩放
            Dimension screenSize = new Dimension(currentImage.getWidth(null), currentImage.getHeight(null));
            double scaleX = getWidth() / (double) screenSize.width;
            double scaleY = getHeight() / (double) screenSize.height;
            double scale = Math.min(scaleX, scaleY);
            int width = (int)(screenSize.width * scale);
            int height = (int)(screenSize.height * scale);
            g.drawImage(currentImage, 0, 0, width, height, this);
        } else {
            g.setColor(Color.WHITE);
            g.setFont(new Font("SansSerif", Font.BOLD, 24));
            g.drawString("等待屏幕图像...", getWidth()/2 - 100, getHeight()/2);
        }
    }
}

增强功能示例

文件传输功能

// 添加文件传输功能到服务器
public void sendFile(String filePath) {
    try {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在: " + filePath);
            return;
        }
        // 发送文件传输命令
        dos.writeUTF("FILE:" + file.getName());
        dos.writeLong(file.length());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
        fis.close();
        dos.flush();
        System.out.println("文件发送完成: " + filePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用说明

启动服务器

java server.RemoteServer

启动客户端

java client.RemoteClient

测试命令

  • SHELL:dir - 在Windows上执行目录列表
  • SHELL:pwd - 显示当前目录
  • MOUSE:CLICK - 模拟鼠标点击
  • SHUTDOWN - 关闭服务器

安全注意事项

  1. 身份验证:生产环境必须添加身份验证机制
  2. 加密传输:建议使用SSL/TLS加密所有通信
  3. 防火墙限制:仅允许受信任的IP地址连接
  4. 会话管理:实现会话超时和访问控制
  5. 操作日志:记录所有远程操作

这个案例提供了一个基础的远程控制系统,可以根据实际需求进行扩展和增强,注意在生产环境中使用时要充分考虑安全性。

抱歉,评论功能暂时关闭!