Based on link1 and link2
It finally turned out that we can get the client IP address with the following two classes, in fact you can do more with open httpservletRequest ...
ServletAwareConfigurator.java
package examples; import java.lang.reflect.Field; import javax.servlet.http.HttpServletRequest; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator; public class ServletAwareConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpServletRequest httpservletRequest = getField(request, HttpServletRequest.class); String sClientIP = httpservletRequest.getRemoteAddr(); config.getUserProperties().put("clientip", sClientIP);
GetHttpSessionSocket.java
package examples; import java.io.IOException; import javax.servlet.http.HttpSession; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/example", configurator = ServletAwareConfigurator.class) public class GetHttpSessionSocket { private Session wsSession; private String sClientIP; @OnOpen public void open(Session session, EndpointConfig config) { this.wsSession = session; this.sClientIP = (String) config.getUserProperties() .get("clientip"); } @OnMessage public void echo(String msg) throws IOException { wsSession.getBasicRemote().sendText(msg); } }
source share