Ir ao conteúdo
  • Cadastre-se

Java Desenvolvendo uma Conexão Remota em JAVA


Posts recomendados

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

 

 

Servidor

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();
        }
    }
}

 

  • Amei 1
Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

Ebook grátis: Aprenda a ler resistores e capacitores!

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!