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);

        }

    }

  • 相关阅读:
    微服务通过feign.RequestInterceptor传递参数
    fastdfs的storage的IP地址映射docker宿主地址
    Sentinel对Feign的支持
    SpringBoot设置MultipartFile文件大小限制
    SpringBoot+JWT@注解实现token验证
    springBoot 使用 mybatis-plus 实现分页
    MyBatis-Plus 使用xml文件
    MAC inode提示:正在查询SSLVPN网关参数... 查询SSLVPN 网关参数失败,请检查网络配置或联系
    MacOS launchctl 启动进程控制
    可执行Jar格式-1
  • 原文地址:https://www.cnblogs.com/stay-sober/p/4158794.html
Copyright © 2011-2022 走看看