Jump to content
Fórum Script Brasil
  • 0

Desenvolvendo uma Conexão Remota em JAVA


Luan Marques

Question

Olá. Estou desenvolvendo um software de conexão remota, mas estou com um problema. Será que alguém pode me ajudar?
O meu código estava funcionando até eu tentar implementar o código para o teclado. Exemplo: Eu fiz um código onde o cliente conectar no servidor, servidor "transmite" a interface em tempo real, eu configurei o clique do mouse esquerdo e direito, menos o scroll e a opção de clicar e arrastar, mas esse não é o problema até agora.
O meu problema é que não está mais sendo transmitido a interface, quando eu faço a conexão abre uma janela em branco e só fica desse jeito, isso aconteceu depois que tentei implementar o teclado

Cliente:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class ClienteSocketComInterface {

    public static void main(String[] args) throws IOException {
        String enderecoServidor = "192.168.8.176";
        int porta = 12345;

        Socket socket = new Socket(enderecoServidor, porta);

        JFrame frame = new JFrame("Cliente - Compartilhamento de Tela, Mouse e Teclado");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension resolucao = new Dimension(1366, 768);

        JLabel screenLabel = new JLabel();
        screenLabel.setPreferredSize(resolucao);
        screenLabel.setHorizontalAlignment(SwingConstants.CENTER);
        screenLabel.setVerticalAlignment(SwingConstants.CENTER);
        screenLabel.setMaximumSize(resolucao);

        JScrollPane scrollPane = new JScrollPane(screenLabel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setViewportView(screenLabel);
        scrollPane.setMaximumSize(resolucao);

        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        frame.setSize(resolucao);
        frame.setResizable(false);
        frame.setVisible(true);

        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Point posicao = e.getPoint();
                enviarComandoMouseTeclado(socket, posicao, SwingUtilities.isLeftMouseButton(e), SwingUtilities.isRightMouseButton(e), '\0');
                SwingUtilities.convertPoint(scrollPane, posicao, screenLabel);
            }
        });

        frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                enviarComandoMouseTeclado(socket, new Point(0, 0), false, false, e.getKeyChar());
            }
        });
        frame.setFocusable(true);

        Thread networkThread = new Thread(() -> {
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                        Image image = (Image) ois.readObject();
                        if (image != null) {
                            SwingUtilities.invokeLater(() -> {
                                screenLabel.setIcon(new ImageIcon(image));
                                screenLabel.repaint();
                                scrollPane.revalidate();
                            });
                        }
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }, 0, 2000);
        });

        networkThread.start();

        frame.pack();
    }

    private static void enviarComandoMouseTeclado(Socket socket, Point point, boolean leftClick, boolean rightClick, char keyChar) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(new ComandoMouseTeclado(point, leftClick, rightClick, keyChar));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Servidor:

package com.luan.conectar;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import javax.imageio.ImageIO;

public class ServidorSocketComInterface {
    private static Robot robot;
    private static double fatorEscalaX = 1.0;
    private static double fatorEscalaY = 1.0;

    public static void main(String[] args) {
        int porta = 12345;

        try {
            ServerSocket servidor = new ServerSocket(porta);
            System.out.println("Aguardando conexão na porta: " + porta + "...");

            Socket cliente = servidor.accept();
            System.out.println("Conexão estabelecida com: " + cliente.getInetAddress().getHostAddress());

            createRobot();

            while (true) {
                receberComandoMouseTeclado(cliente);
                enviarCapturaTela(cliente);
            }
        } catch (IOException | AWTException e) {
            e.printStackTrace();
        }
    }

    private static void createRobot() throws AWTException {
        robot = new Robot();
    }

    private static void receberComandoMouseTeclado(Socket cliente) {
        try {
            ObjectInputStream ois = new ObjectInputStream(cliente.getInputStream());
            Object object = ois.readObject();

            if (object instanceof ComandoMouseTeclado) {
                ComandoMouseTeclado comando = (ComandoMouseTeclado) object;

                int mouseXCliente = comando.getPoint().x;
                int mouseYCliente = comando.getPoint().y;
                boolean leftClick = comando.isLeftClick();
                boolean rightClick = comando.isRightClick();
                char keyTyped = comando.getKeyChar();

                int mouseXServidor = mapearCoordenadaX(mouseXCliente, fatorEscalaX);
                int mouseYServidor = mapearCoordenadaY(mouseYCliente, fatorEscalaY);

                robot.mouseMove(mouseXServidor, mouseYServidor);

                if (leftClick) {
                    robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
                    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
                }

                if (rightClick) {
                    robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
                    robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static int mapearCoordenadaX(int coordenadaClienteX, double fatorEscalaX) {
        return (int) (coordenadaClienteX * fatorEscalaX);
    }

    private static int mapearCoordenadaY(int coordenadaClienteY, double fatorEscalaY) {
        return (int) (coordenadaClienteY * fatorEscalaY);
    }

    private static void enviarCapturaTela(Socket cliente) {
        try {
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage capture = robot.createScreenCapture(screenRect);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(capture, "png", baos);
            baos.flush();
            byte[] imageBytes = baos.toByteArray();
            baos.close();

            DataOutputStream dos = new DataOutputStream(cliente.getOutputStream());
            dos.writeInt(imageBytes.length);
            dos.write(imageBytes, 0, imageBytes.length);
            dos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.1k
    • Total Posts
      651.8k
×
×
  • Create New...