springboot/spring4.0获取websocket请求ip
众所周知,JSR-356对websocket的支持是通过http ugrade上来的,打断点可以看到,而标准的Session(WebSocketSession) 在规范中并没有ip。所以需要通过WebFilter的方式在HTTPSession中放入,在握手的时候使用modifyHandshake获取IP。
具体步骤
- 在Filter中request.getSession() ,然后将HttpServletRequet.getRemoteAddr()存入map。
- 继承ServerEndpointConfig.Configurator,重写modifyHandshake方法。将 HTTPSession的值写入ServerEndpointConfig.UserProperties中。
- @ServerEndPoint(config=你刚刚继承的Configurator类。
具体代码
package com.app.modular.filter;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@javax.servlet.annotation.WebFilter(filterName = "sessionFilter",urlPatterns = "/*")
@Order(1)
public class WebFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req= (HttpServletRequest) request;
req.getSession().setAttribute("ip",req.getRemoteHost());
chain.doFilter(request,response);
}
}
package com..app.config;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Enumeration;
import java.util.Map;
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {
public static final String HTTP_SESSION_ID_ATTR_NAME = "HTTP.SESSION.ID";
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
Map<String, Object> attributes = sec.getUserProperties();
HttpSession session = (HttpSession) request.getHttpSession();
if (session != null) {
attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
attributes.put(name, session.getAttribute(name));
}
}
}
}
@ServerEndpoint(value = "/mysocket",configurator = WebSocketConfigurator.class)
@Controller
public class AppEntryPoint {
@OnMessage
public String msg(String msg, Session session) {
log.info("收到消息" + msg);
}
}
别忘了在启动类上打注解扫描Filter@ServletComponentScan(basePackages = {"com.aaa"})
原文https://stackoverflow.com/questions/22880055/jsr-356-websockets-with-tomcat-how-to-limit-connections-within-single-ip-addre