Codigo travando ao realizar ping com INetAddress

8 respostas Resolvido
java
I

Salve familia, sou iniciante no mundo e tou tentando fazer um programa de monitoramento que ping para varios ips e de acordo com o retorno muda a cor do JPanel criado. Até aqui consegui fazer o teste de ping, porem percebi que o retorno é lento, talvez seja até isso que está implicando com o codigo pois a criacaçao do paineis está rodando tranquilo. segue o codigo:

import javax.swing.<em>;

import java.awt.</em>;

import java.util.ArrayList;

import java.util.Arrays;
public class Screen extends Pingar{

JPanel [][] jPanels = new JPanel[170][100];

JFrame jFrame1 = new JFrame();

JPanel jPanel = new JPanel();

JPanel titulo = new JPanel();

JLabel [][] textip = new JLabel[1700][1000];

public void Painel1(){

jFrame1.setVisible(true);

jFrame1.setTitle(PINGS);

jFrame1.setSize(800,6000);

jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jFrame1.setLocationRelativeTo(null);
Pingar p = new Pingar();
    String [] ip = new String[1900];
    for(int i = 0 ; i < 170 ; i++){
        for (int j = 0 ; j < 30 ; j++){
            int z = 10;
            if(j < 5){
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.red);
                jPanels[i][j].setPreferredSize(new Dimension(100,100));
                jPanels[i][j].setOpaque(true);
                textip[i][j].setFont(new Font("Arial",Font.BOLD,20));
                textip[i][j].setText("10.10." + (i+1) + "." + (j+1));
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);
            }else if (j > 9 && j < 15){
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.red);
                jPanels[i][j].setPreferredSize(new Dimension(100,100));
                jPanels[i][j].setOpaque(true);
                textip[i][j].setFont(new Font("Arial",Font.BOLD,20));
                textip[i][j].setText("10.10." + (i + 1) + "." + (j+1));
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);
            }else if (j > 15){
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.red);
                jPanels[i][j].setPreferredSize(new Dimension(100,100));
                jPanels[i][j].setOpaque(true);
                textip[i][j].setFont(new Font("Arial",Font.BOLD,20));
                textip[i][j].setText("10.10." + (i+1) + "." + 250);
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);
                break;
            }
        }
    }
    jPanel.setLayout(new GridLayout(0,11,10,10));



    JScrollPane scrool = new JScrollPane(jPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    JLabel tituloLabel = new JLabel("PINGTEST");
    tituloLabel.setFont(new Font("Arial",Font.BOLD,30));
    titulo.add(tituloLabel);

    jFrame1.setLayout(new BorderLayout());
    jFrame1.add(tituloLabel,BorderLayout.NORTH);
    jFrame1.add(scrool,BorderLayout.CENTER);

}



public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new Screen().Painel1());
}

}

import java.net.InetAddress;

public class Pingar {

private String ip;

private final int maxTemp = 10;
public boolean PingTo(String ip) {
    try {
        InetAddress address = InetAddress.getByName(ip);
        return address.isReachable(this.maxTemp);
    } catch (Exception e) {
        System.out.println(e);
    }
    return false;
}

//METODOS ESPECIAIS
public String getIp() {
    return ip;
}

public void setIp(String ip) {
    this.ip = ip;
}

}

Tou precisando desse help. Iniciei a pouco tempo quero só uma luz para dar continuidade. Esses ips são do dominio, são 170 lojas com + - 10 computadores cada.

8 Respostas

S

Nesse código que você postou, em nenhum momento é chamado o método PingTo (Em maiúsculo?).

I

Olá staroski. Desculpa, é que eu removi por engano, ia comentar ele e removi. Mas ele ficaria dentro dos IFS que estão dentro do laço, se o retorno de PingTo fosse true deixaria o jPanels[i][j] com a cor verde, se não continuaria vermelho. E tipo esse PingTo teria que ficar atualizando o painel de 30 em 30 segundos, será que dá pra fazer?

S

Posta o código atualizado pois aí tem muita coisa estranha:

  • você tem uma matriz de JPanel de 17.000 posições;
  • uma matriz de JLabel de 1.700.000 posições;
  • um array de String de 1.900 posições.
I
import javax.swing.<em>;

import java.awt.</em>;

import java.net.InetAddress;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.concurrent.*;
public class Screen implements Runnable {

JPanel[][] jPanels = new JPanel[170][100];

JFrame jFrame1 = new JFrame();

JPanel jPanel = new JPanel();

JPanel titulo = new JPanel();

JLabel[][] textip = new JLabel[1700][1000];
public void Painel1() {
    jFrame1.setVisible(true);
    jFrame1.setTitle("PINGS");
    jFrame1.setSize(800, 6000);
    jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame1.setLocationRelativeTo(null);
    Thread ip = new Thread(() -> run());

    for (int i = 0; i < 170; i++) {
        for (int j = 0; j < 30; j++) {
            int z = 10;
            if (j < 4) {
                //CRIAR PAINES E TEXTOS
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.LIGHT_GRAY);
                textip[i][j].setFont(new Font("Arial", Font.BOLD, 20));
                textip[i][j].setText("www.google.com"/*"10.10." + (i + 1) + "." + (j + 1)*/);
                jPanels[i][j].setPreferredSize(new Dimension(100, 100));
                jPanels[i][j].setOpaque(true);
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);

            } else if (j > 9 && j < 14) {
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.LIGHT_GRAY);
                jPanels[i][j].setPreferredSize(new Dimension(100, 100));
                jPanels[i][j].setOpaque(true);
                textip[i][j].setFont(new Font("Arial", Font.BOLD, 20));
                textip[i][j].setText("10.10." + (i + 1) + "." + j);
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);

            } else if (j > 15) {
                jPanels[i][j] = new JPanel();
                textip[i][j] = new JLabel();
                jPanels[i][j].setBackground(Color.LIGHT_GRAY);
                jPanels[i][j].setPreferredSize(new Dimension(100, 100));
                jPanels[i][j].setOpaque(true);
                textip[i][j].setFont(new Font("Arial", Font.BOLD, 20));
                textip[i][j].setText("10.10." + (i + 1) + "." + 250);
                jPanels[i][j].add(textip[i][j]);
                jPanel.add(jPanels[i][j]);
                break;
            }
        }
    }
    jPanel.setLayout(new GridLayout(0, 9, 10, 10));


    JScrollPane scrool = new JScrollPane(jPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    JLabel tituloLabel = new JLabel("PINGTEST");
    tituloLabel.setFont(new Font("Arial", Font.BOLD, 30));
    titulo.add(tituloLabel);

    jFrame1.setLayout(new BorderLayout());
    jFrame1.add(tituloLabel, BorderLayout.NORTH);
    jFrame1.add(scrool, BorderLayout.CENTER);


    ip.start();

}

// Aqui tentei fazer um thead pois como havia dito tava travando meu codigo, até então fucionou, só //que tem um problema, quando o retorno do address é false demora um pouco ai torna o codigo //lento;

@Override
public void run() {
    final int maxTemp = 100;
    for (int i = 0; i < 170; i++) {
        for (int j = 0; j < 30; j++) {
            int z = 10;
            if (j < 4) {
                if(this.textip[i][j] != null){
                    try {
                        InetAddress address = InetAddress.getByName(textip[i][j].getText());
                        if(address.isReachable(maxTemp)){
                            jPanels[i][j].setBackground(Color.green);
                        }else {
                            jPanels[i][j].setBackground(Color.red);
                        }
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            } else if (j > 9 && j < 14) {
                try {
                    InetAddress address = InetAddress.getByName(textip[i][j].getText());
                    if(address.isReachable(maxTemp)){
                        jPanels[i][j].setBackground(Color.green);
                    }else {
                        jPanels[i][j].setBackground(Color.red);
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            } else if (j > 15) {
                try {
                    InetAddress address = InetAddress.getByName(textip[i][j].getText());
                    if(address.isReachable(maxTemp)){
                        jPanels[i][j].setBackground(Color.green);
                    }else {
                        jPanels[i][j].setBackground(Color.red);
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
                break;
            }
        }
    }
}

public static void main(String[] args) {
    Screen teste = new Screen();
    teste.Painel1();
}

}

Eu tava pensando se seria mais viavel, fazer o seguinte por exemplo tem 170 lojas cada uma com + ou menos 11 IPS(por isso a quantidade de paineis nesse codigo aí), daí era melhor criar um jtext que receberia o numero de uma loja pelo usuário, dai só criaria 11 paineis já que os IPS são padrão e só muda o numero da loja “10.10. N°LOJA .X”.
A questão de ter varios paineis seria somente para monitoramento entende?

S

Mas 170 * 11 é bem diferente de 1700 * 1000…

Dá uma olhada no exemplo abaixo, talvez ajude:

import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExemploPing {

	private static final int PING_TIMEOUT = 1000; // 1 segundo de timeout

	private static class Ping implements Runnable {

		private final String nome;
		private final String ip;

		public Ping(String nome, String ip) {
			this.nome = nome;
			this.ip = ip;
		}

		private boolean isReachable(String ip) {
			try {
				InetAddress address = InetAddress.getByName(ip);
				return address.isReachable(PING_TIMEOUT);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		public void run() {
			String status = isReachable(ip) ? "online" : "offline";
			System.out.println(nome + " - IP " + ip + " - " + status);
		}
	}

	private static class Loja {

		private String nome;
		private String[] ips;

		public Loja(String nome, String... ips) {
			this.nome = nome;
			this.ips = ips;
		}
	}

	public static void main(String[] args) {
		try {
			ExemploPing programa = new ExemploPing();
			programa.executar();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private void executar() {
		Loja[] lojas = new Loja[] {
				new Loja("Loja 1", "ip1", "ip2", "ip3"),
				new Loja("Loja 2", "ip1", "ip2", "ip3"),
				new Loja("Loja 3", "ip1", "ip2", "ip3"),
				new Loja("Loja 4", "ip1", "ip2", "ip3"),
				new Loja("Loja 5", "ip1", "ip2", "ip3")
				// tantas lojas e ips quantas você tiver...
		};

		// vamos usar 1 Thread por loja
		int quantidadeThreads = lojas.length;

		// Criando um pool de threads
		ExecutorService executor = Executors.newFixedThreadPool(quantidadeThreads);

		for (Loja loja : lojas) {
			for (String ip : loja.ips) {
				executor.execute(new Ping(loja.nome, ip));
			}
		}

		// Encerrando o pool de threads
		executor.shutdown();

		try {
			// Aguardando todas as threads concluírem ou um timeout de 10 segundos
			executor.awaitTermination(10, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
I
Cara, pior que eu estava pensando em fazer isso ai também. É até melhor que eu tenho mais controle sobre os IPS.

Pode me explicar esse essas linhas?,  esse  " : " o que signifa.

for (Loja loja : lojas) {

for (String ip : loja.ips) {

executor.execute(new Ping(loja.nome, ip));

}

}
S
Solucao aceita

Segue um exemplo funcional que atualiza a cor dos labels.
Só precisa ajustar com as informações de suas lojas e seus IPs.

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class ExemploPing {

	// classe interna para armazenar o nome e os IPs de cada loja
	private static class Loja {

		private String nome;
		private String[] ips;

		public Loja(String nome, String... ips) {
			this.nome = nome;
			this.ips = ips;
		}
	}

	// classe interna para executar um ping e atualizar a cor de um label
	private static class Ping implements Runnable {

		private JLabel label;
		private final String nome;
		private final String ip;

		public Ping(JLabel label, String nome, String ip) {
			this.label = label;
			this.nome = nome;
			this.ip = ip;
		}

		@Override
		public void run() {
			Color color = isReachable(ip) ? Color.GREEN.brighter() : Color.RED.brighter();
			label.setBackground(color);
		}

		private boolean isReachable(String ip) {
			try {
				InetAddress address = InetAddress.getByName(ip);
				return address.isReachable(1000);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
	}

	public static void main(String[] args) {
		try {
			ExemploPing programa = new ExemploPing();
			programa.executar();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private void executar() {
		Loja[] lojas = new Loja[] { //
				new Loja("Loja 1", "ip1", "ip2", "ip3"),
				new Loja("Loja 2", "ip1", "ip2", "ip3"),
				new Loja("Loja 3", "ip1", "ip2", "ip2"),
				new Loja("Loja 4", "ip1", "ip2", "ip3"),
				new Loja("Loja 5", "ip1", "ip2", "ip3")
				 // tantas lojas e ips quantas você tiver...
		};
		List<Ping> pings = new ArrayList<>(); // a lista de pings que serão executados.

		apresentaTela(lojas, pings);

		// Criando um pool de threads usando 1 Thread por loja
		ExecutorService executor = Executors.newFixedThreadPool(lojas.length);
		Thread thread = new Thread(() -> executarPings(executor, pings));
		thread.start();
	}

	private void apresentaTela(Loja[] lojas, List<Ping> pings) {
		JFrame frame = new JFrame("Exemplo Ping");
		frame.setMinimumSize(new Dimension(800, 600));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container panel = frame.getContentPane();
		panel.setLayout(new GridLayout(5, 3)); // aqui você vai ajustar o layout à suas necessidades
		for (Loja loja : lojas) {
			String nome = loja.nome;
			for (String ip : loja.ips) {
				JLabel label = new JLabel(
						"<html><div style='text-align: center;'>" + nome + "<br/>IP: " + ip + "</div></html>",
						SwingConstants.CENTER);
				label.setOpaque(true);
				panel.add(label);
				pings.add(new Ping(label, nome, ip)); // criando um objeto Ping que vai atualizar o label
			}
		}
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}

	private void executarPings(ExecutorService executor, List<ExemploPing.Ping> pings) {
		while (true) {
			for (Ping ping : pings) {
				executor.execute(ping); // aqui vai executar o método run da classe Ping
			}
			try {
				Thread.sleep(5000); // re-executar os pings a cada 5 segundos
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

Isso se chama “enhanced for”, o código é equivalente a fazer:

for (int i = 0; i < lojas.size(); i++) {
	Loja loja = lojas.get(i);

    for (for int j = 0; j < loja.ips.length; j++) {
		String ip = loja.ips[j];

        executor.execute(new Ping(loja.nome, ip));
    }
}
I

Cara, muito obrigado. Vou estudar seu código e tentar replicar, é exatamente oque eu estava tentando fazer.
tenho que estudar ainda um pouco mais para fazer esse tipo de projeto só. De qualquer forma obrigado me ajudou pra caramba.

Criado 14 de janeiro de 2024
Ultima resposta 18 de jan. de 2024
Respostas 8
Participantes 2