zoukankan      html  css  js  c++  java
  • Java推断和检查网络

    在实践项目中。常常要处理网络异常等问题。为此,专门设计一个类,随时能够使用。

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.UnknownHostException;
    import java.util.Enumeration;
    
    /**
     * @author administrator
     *
     */
    public class NetworkMonitor implements Runnable {
    	private String m_strUrl = "192.168.1.27";
    	private static boolean m_bNetworkAvailable = false;
    	
    	/**
    	 * 
    	 */
    	public NetworkMonitor() {
    		// TODO:
    	}
    	
    	/**
    	 * @param strUrl
    	 */
    	public NetworkMonitor(String strUrl) {
    		this.m_strUrl = strUrl;
    	}
    	
    	/**
    	 * @return
    	 */
    	public static boolean isNetworkAvailable() {
    		return m_bNetworkAvailable;
    	}
    	
    	/* (non-Javadoc)
    	 * @see java.lang.Runnable#run()
    	 */
    	@Override
    	public void run() {
    		while (true) {
    			try {
    				InetAddress inetAddress = InetAddress.getByName(m_strUrl);
    				m_bNetworkAvailable = inetAddress.isReachable(5000);		//測试能否够达到该地址
    				
    				Thread.sleep(2000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				// e.printStackTrace();
    				m_bNetworkAvailable = false;
    			} catch(UnknownHostException e) {
    				// System.err.println("连接失败");
    				m_bNetworkAvailable = false;
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				// e.printStackTrace();
    				m_bNetworkAvailable = false;
    			}
    		}
    	}
    	
    	public void isAddressAvailable(String ip) { 
    		try { 
    			InetAddress address = InetAddress.getByName(ip);	//ping this IP 
    			if (address instanceof java.net.Inet4Address) {
    				System.out.println(ip + " is ipv4 address"); 
    				} else if (address instanceof java.net.Inet6Address) {
    					System.out.println(ip + " is ipv6 address"); 
    				} else {
    					System.out.println(ip + " is unrecongized"); 
    				}
    
            if (address.isReachable(5000)) {
            	System.out.println("SUCCESS - ping " + ip + " with no interface specified"); 
            } else {
            	System.out.println("FAILURE - ping " + ip + " with no interface specified"); 
            }
            
            System.out.println("
    -------Trying different interfaces--------"); 
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); 
            while (netInterfaces.hasMoreElements()) {
            	NetworkInterface ni = netInterfaces.nextElement(); 
            	System.out.println( "Checking interface, DisplayName:" + ni.getDisplayName() + ", Name:" + ni.getName());
            	if(address.isReachable(ni, 0, 5000)){ 
            		System.out.println("SUCCESS - ping " + ip);
            	} else {
            		System.out.println("FAILURE - ping " + ip); 
            	}
            	Enumeration<InetAddress> ips = ni.getInetAddresses();
            	while(ips.hasMoreElements()) { 
            		System.out.println("IP: " + ips.nextElement().getHostAddress()); 
            	}
            	System.out.println("-------------------------------------------"); }
            } catch (Exception e) {
            	System.out.println("error occurs."); 
            	e.printStackTrace(); 
            } 
    	}
    }
    实际中须要知道网络状态的时候,不必专门去再检查。由于那样可能会堵塞,导致调用者挂起,在这里直接调用isNetworkAvailable方法能够马上知道网络状态,所以性能不会受到不论什么影响。

    这个类以下实现的线程run方法中,检查网络也是2秒钟检查一次,不会影响整个程序的性能。假设有更高的要求,能够改成1秒或者0.5秒。我的意见是2秒够了。

    由于网络断开非常快,可是要恢复也是须要点时间的,所以不必重复检查。那样会影响性能。

    调用演示样例:

    public class Startup { 
    	
    	/**
    	 * @see 应用程序入口
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Startup startup = new Startup();
    		startup.startNetworkMonitor();
    		
    		for (int i = 0; i < 60; i++) {
    			System.out.println("network[" + i + 1 +"]: " + NetworkMonitor.isNetworkAvailable());
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    	
    	public void startNetworkMonitor() {
    		NetworkMonitor networkMonitor = new NetworkMonitor();
    		networkMonitor.isAddressAvailable("192.168.1.1");
    		Thread thread = new Thread(networkMonitor);
    		thread.start();
    		
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }

    试执行就能够知道。 这一句

    System.out.println("network[" + i + 1 +"]: " + NetworkMonitor.isNetworkAvailable());

    全然就是毫秒级返回。各方面表现很理想。

  • 相关阅读:
    命令[34]
    命令[33]
    命令[27]
    命令[38]
    命令[19]
    命令[22]
    命令[30]
    命令[37]
    命令[23]
    命令[26]
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7133822.html
Copyright © 2011-2022 走看看