The websocket protocol is similar to the http protocol, and also has its own header information, as shown in the figure below, which is the header customized by postman when connecting:
So in the backend, how to HttpServletRequest
get the content of this header information like http?
-
Customize a WebSocket configuration class:
modifyHandshake()方法:
When the handshake is established, the operation before the connection can obtain the source information and pass it to the SessiongetEndpointInstance()方法:
Initialize the endpoint object, which is the object marked by @ServerEndpoint
@Configuration public class WebSocketConfig extends ServerEndpointConfig.Configurator { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } /** * 建立握手时,连接前的操作 */ @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { // 这个userProperties 可以通过 session.getUserProperties()获取 final Map<String, Object> userProperties = sec.getUserProperties(); Map<String, List<String>> headers = request.getHeaders(); List<String> remoteIp = headers.get("x-forwarded-for"); List<String> header1 = headers.get("x1"); List<String> header2 = headers.get("x2"); userProperties.put("header1", header1.get(0)); userProperties.put("header2", header2.get(0)); userProperties.put("x-forwarded-for", remoteIp.get(0)); } /** * 初始化端点对象,也就是被@ServerEndpoint所标注的对象 */ @Override public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException { return super.getEndpointInstance(clazz); } }
-
@ServerEndpoint(value = "/websocket/document",configurator = WebSocketConfig.class)
Specify our custom configuration class in . -
Encapsulate a method to get header information
public static String getHeader(Session session, String headerName) { final String header = (String) session.getUserProperties().get(headerName); if (StrUtil.isBlank(header)) { log.error("获取header失败,不安全的链接,即将关闭"); try { session.close(); } catch (IOException e) { e.printStackTrace(); } } return header; }
-
You can use it anywhere you can get the Session
@OnMessage public void onMessage(Session session, String message) { log.info("client received message:{}, session:{},", message,session.hashCode()); final String header = WebSocketUtil.getHeader(session, "header1"); try { session.getBasicRemote().sendText(header); } catch (IOException e) { e.printStackTrace(); } }
It is worth noting that:
- The Configurator implementation class is only executed once when the endpoint is initialized
- Other follow-up encounters will come back to make up...