zoukankan      html  css  js  c++  java
  • socket编程2-ConnectTester

    package Chapter2;

    import java.io.IOException;
    import java.net.*;

    public class ConnectTester {
        public static void main(String[] args) {
            String host = "localhost";
            int port = 8000;
            if (args.length > 1) {
                host=args[0];
                port = Integer.parseInt(args[1]);
            }
            new ConnectTester().connect(host, port);
        }

        public void connect(String host, int port) {
            //
            SocketAddress remoteAdd = new InetSocketAddress(host, port);
            Socket socket = null;
            String result = "";
            try {
                long begin = System.currentTimeMillis();
                socket = new Socket();
                socket.connect(remoteAdd, 10000);//最长连接用时为10秒
                long end = System.currentTimeMillis();
                result = (end - begin) + "ms";
            } catch (BindException e) {
                result = "Local address and port can`t be binded";
            } catch (UnknownHostException e) {
                result = "Unknown Host";
            } catch (ConnectException e) {
                result = "ConnectException";
            } catch (SocketTimeoutException e) {
                result = "TimeOut";
            } catch (IOException e) {
                result = "failure";
            } finally {
                try {
                    if (socket != null)
                        socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("访问:"+socket.getRemoteSocketAddress()+"连接用时" + result);

        }

    }

  • 相关阅读:
    前端开发网址
    Iconfot阿里妈妈-css高级应用
    手机端的META你知道多少?
    24个 HTML5 & CSS3 下拉菜单效果及制作教程
    css :clip rect 正确的使用方法
    layui :iframe 与 layer 的位置问题
    时间戳转现实时间的方法
    关于 iframe 的小问题若干
    使用 forever 启动 vue 需要注意的问题
    var 的一个坑,以及 let
  • 原文地址:https://www.cnblogs.com/stay-sober/p/4158794.html
Copyright © 2011-2022 走看看