• java获取ip地址慢,webSocket获取ip



    java 中 InetSocketAddress

    remoteAddress.getHostName() //获取hostName时耗时长,改方法要慎用;(先从本地取,如果本地没取到从远程dns中取)
    remoteAddress.getAddress().getHostAddress() ; //改用这种方式获取ip

    public class WebsocketUtil {

    public static InetSocketAddress getRemoteAddress(Session session) {
    if (session == null) {
    return null;
    }
    Async async = session.getAsyncRemote();

    //在Tomcat 8.0.x版本有效
    // InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#sos#socketWrapper#socket#sc#remoteAddress");
    //在Tomcat 8.5以上版本有效
    InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#socketWrapper#socket#sc#remoteAddress");
    return addr;
    }

    private static Object getFieldInstance(Object obj, String fieldPath) {
    String fields[] = fieldPath.split("#");
    for (String field : fields) {
    obj = getField(obj, obj.getClass(), field);
    if (obj == null) {
    return null;
    }
    }

    return obj;
    }

    private static Object getField(Object obj, Class<?> clazz, String fieldName) {
    for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
    try {
    Field field;
    field = clazz.getDeclaredField(fieldName);
    field.setAccessible(true);
    return field.get(obj);
    } catch (Exception e) {
    }
    }

    return null;
    }

    }

     
    盛世岂埋凌云气,年少无为就努力
  • 相关阅读:
    Java实现 LeetCode 402 移掉K位数字
    Java实现 LeetCode 402 移掉K位数字
    Java实现 LeetCode 401 二进制手表
    Java实现 LeetCode 401 二进制手表
    wpa_supplicant使用笔记-wpa_cli iwconfig
    Linux下的定时器:alarm()与setitimer()
    在 Windows 下远程桌面连接 Linux
    assert()函数用法总结
    linux下svn修改用户名和密码
    VirtualBox
  • 原文地址:https://www.cnblogs.com/guangchuantang/p/14652219.html
Copyright © 2020-2023  润新知