首页 > 其他 > 详细

3、Socket-连接异常测试

时间:2016-05-20 18:57:33      阅读:121      评论:0      收藏:0      [点我收藏+]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * @name Socket连接异常测试
 * @author wujianxiong
 * @date 2016-5-20
 */
public class ConnectTester {
    
    public static void main(String[] args){
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        String host = "127.0.0.1";
        int port = 139;
        try {
            String msg = reader.readLine();
            //直接敲回车结束循环
            while(!msg.isEmpty()&& msg!=null){
                String[] strArr = msg.split(" ");
                host = strArr[0];
                port = Integer.parseInt(strArr[1]);
                //测试连接
                ConnectTester.connect(host, port);
                msg = reader.readLine();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
    public static void connect(String host,int port){
        
        SocketAddress remoteAddress = new InetSocketAddress(host, port);
        
        Socket socket = new Socket();
        try {
            long beginTime = System.currentTimeMillis();
            socket.bind(new InetSocketAddress("10.0.5.128", 80));
            socket.connect(remoteAddress, 1000);
            
            long endTime = System.currentTimeMillis();
            System.out.println(remoteAddress+" take "+(endTime-beginTime)+"ms to connect");
        } catch (BindException e) {
            System.out.println("Local address and port can‘t be binded");
        } catch (UnknownHostException e) {
            // TODO: handle exception
            System.out.println("UnKnown Host");
        } catch (ConnectException e) {
            System.out.println("Connect Refused");
        } catch (SocketTimeoutException e) {
            System.out.println("Time Out");
        } catch (IOException e) {
            System.out.println("Failed");
        } finally{
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
}

 

3、Socket-连接异常测试

原文:http://www.cnblogs.com/nan5-3-105/p/5512892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!