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

        }

    }

  • 相关阅读:
    Flask_自定义参数类型(自定义转换器)
    数据结构与算法(排序)
    数据结构与算法(查找)
    Vue_fetch和axios数据请求
    Vue_修饰符
    Vue_列表过滤应用
    Vue_生命周期函数
    Vue_watch()方法,检测数据的改变
    Django_redis_缓存
    防火墙相关
  • 原文地址:https://www.cnblogs.com/stay-sober/p/4158794.html
Copyright © 2020-2023  润新知