使用ServerEndpoint时获取客户端IP地址

时间:2016-05-31 10:20:43

标签: java-ee java-websocket

意味着它将从本地Web中的许多用户获得连接。如何获得每个连接的IP地址?我使用JSR356。

@ServerEndpoint(value = "/ws/example")
public class ExampleServlet {

     private static final AtomicInteger connectionIds = new AtomicInteger(0);
     private static final Set<ExampleServlet> connections = new CopyOnWriteArraySet<>();
     private Session session;

     @OnOpen
     public void start(Session session) {
         this.session = session;
         connections.add(this);
     }

     @OnClose
     public void end() {
     }

     @OnMessage
     public void incoming(String message) {
     }

     @OnError
     public void onError(Throwable t) throws Throwable {
     }
}

2 个答案:

答案 0 :(得分:1)

不幸的是,JSR356 Websocket规范不公开客户端IP地址。解决方案,如何破解这个,我找到了:JSR-356 WebSockets with Tomcat - How to limit connections within single IP address?

答案 1 :(得分:-1)

这适用于带弹簧的websocket         @覆盖             public void afterConnectionEstablished(WebSocketSession session)抛出Exception {                       的System.out.println(&#34;!connectionestablished&#34 + session.getLocalAddress());
    }