VM冻结检查来自服务器的ping

时间:2014-03-09 05:02:58

标签: java swing virtual-machine ping bluej

我正在尝试编写一个程序来检查来自传奇服务器联盟的ping。我使用命令提示符ping命令在方法中ping服务器。但是,当我单击应调用该方法的按钮时,虚拟机会冻结,而system.print.out.ln会打印出ping号。我试图在面板上进行ping显示而不是终端窗口。请建议。

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Panel03 extends JPanel
{
    // instance variables - replace the example below with your own
    private JLabel label1;
    private JLabel label2;

    public Panel03()
    {
        JButton ping = new JButton("ping");
        ping.addActionListener(new Listener1());
        add(ping);

        JButton quitButton = new JButton("Quit"); 
        quitButton.addActionListener(new Listener());
        add(quitButton);

        setLayout(new FlowLayout());
        label1= new JLabel ("0.0");
        label1.setFont(new Font("Serif", Font.BOLD, 20));
        label1.setForeground(Color.blue);
        add(label1);

    }

    /**
     * An example of a method - replace this comment with your own
     * 
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y 
     */
    private class Listener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    private class Listener1 implements ActionListener
    {
        public void actionPerformed(ActionEvent x)
        {

            try
            {
                Runtime rt = Runtime.getRuntime();
                Process pr = rt.exec("ping riot.ca -t");

                BufferedReader input =
                    new BufferedReader(
                        new InputStreamReader(pr.getInputStream()));

                String line=null;

                while((line=input.readLine()) != null) 
                {
                    System.out.println(line);
                    label1.setText(line);
                }

                int exitVal = pr.waitFor();
                //System.out.println("Exited with error code "+exitVal);

            }
            catch(Exception e)
            {
                System.out.println(e.toString());
                e.printStackTrace();
            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

input.readLine()永远不会是null,因为ping host -t永远不会停止ping,因此输入将永远循环。删除-t,这会导致出现一些输出。

如果您使用的是IDE,那么我建议您通过设置断点和调试循环来试验它。您会注意到它永远不会停止,这会导致应用程序看起来冻结。