Preliminary study on Springboot-websocket-getting httpsession problem

Source: Internet
Author: User
Tags stomp

For a new job, the first task is related to this, did not contact before, no way, various degrees Niang, Google, most of them are words, or is a specific configuration environment is not affixed to the configuration ...

WebSocket protocol

WebSocket is a protocol for full-duplex communication on a single TCP connection. The WebSocket communication protocol was established by the IETF as standard RFC 6455 in 2011 and supplemented by the RFC7936 specification. The WebSocket API has also been established as a standard by the consortium.

WebSocket makes data exchange between client and server easier, allowing the service side to proactively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake, the two directly can create a persistent connection, and two-way data transfer

Stomp protocol

Stomp is a text-oriented message delivery protocol. The STOMP client communicates with a message agent that supports the STOMP protocol. Stomp uses different commands, such as connection, send, subscribe, disconnect, etc. to communicate.

Specific reference: Official introduction

Sockjs

Sockjs is a JavaScript library that provides cross-browser JavaScript APIs, creating a low-latency, full-duplex browser and communication channel between Web servers

The above content is from Wikipedia and Baidu Encyclopedia

Environment configuration
    1. SpringBoot2.0 Family Bucket
    2. In particular, many servers now support WebSocket, and this time I write code with springboot built-in Tomcat
Application Scenarios
    1. If you simply configure a connection to send messages, it is not difficult, specific client writing reference this rookie tutorial-websocket
    2. I need to solve the problem is: when the client and the server to establish a connection, the login user information is removed from HttpSession, the difficulty is that the WebSocket request and HTTP request is completely irrelevant, so there is no way to directly get HttpSession
Implementation ideas
    1. Server-side coding implementation, specifically two sets of solutions
      1. Using inheritance in this way, I look at the official spring document when it seems to be implemented this way
      2. How to use annotations: very painful is the way our project is used.
    2. Specific ideas
      1. Although WebSocket requests are completely unrelated to HTTP requests, endpoint supports reading a configuration if annotations are based
      2. My idea was to intercept or get httpsession in the configuration, it turns out that the idea is correct, but when I follow this idea Baidu Google found that all the gains are null, and then I collapsed
Specific coding implementation
  1. Stick to core code, complete project at the bottom of this article, I put it on GitHub.
  2. First-on-core server-side message processing classes

    /*** WebSocket The main message class * @authorHou Yefei */ //onfigurator = Websocketconfig.class This property is what I mentioned above that we can configure ourselves.@ServerEndpoint(Value ="/api/websocket", Configurator = Websocketconfig.class)@Component@Slf4j Public classWebSocket {/ * There will be a new session object for each browser connection * /    PrivateSession session;/ * is used to store sessions for each session, static is not instantiated * /    Private StaticCopyonwritearrayset<websocket> websocketsets =NewCopyonwritearrayset<> ();/*** Mainly used to listen for connection Setup, config is used to get configuration information in Websocketconfig     * @param session     * @param config     */    @OnOpen     Public void OnOpen(Session session, Endpointconfig config) {log.Info("config:{}", CONFIG.getuserproperties().Get("Name")); Log.Info("session:{}", CONFIG.getuserproperties().Get("SessionID")); This.Session= Session; Websocketsets.Add( This); Log.Info(" websocket message" has a new connection, total: {} ", Websocketsets.size()); }@OnClose     Public void OnClose() {websocketsets.Remove( This); Log.Info(" " websocket message "Connection broken, total: {}", Websocketsets.size()); }@OnError     Public void OnError(Throwable E, Session session) {websocketsets.Remove( This); Log.Info(" " websocket message "connection error or socket not closed:"+ E.GetMessage()); }@OnMessage     Public void OnMessage(String message, session session) { for(WebSocket ws:websocketsets) {ws.Session.Getasyncremote().SendText("Broadcast:"+message); } log.Info(" WebSocket Message" received a message from the client: {} ", message); }}
  3. The following code is the core configuration class

    /*** Main Configuration Classes* This class must inherit configurator because the Config property in the @serverendpoint annotation only receives this type * @authorHou Yefei * */@Configuration@Slf4j Public classWebsocketconfigextendsServerendpointconfig.Configurator{Private Static FinalString HttpSession =NULL;/* Modify the handshake by modifying the contents of the handshake before it is established * /    @Override     Public void Modifyhandshake(serverendpointconfig sec, handshakerequest request, handshakeresponse response) {/ * If there is no listener, then the httpsession obtained here is null*/Standardsessionfacade SSF = (standardsessionfacade) request.gethttpsession();if(SSF! =NULL{HttpSession session = (HttpSession) request.gethttpsession(); Sec.getuserproperties().put("SessionID", session); Log.Info("Get to the sessionid:{}", session.getId()); } sec.getuserproperties().put("Name","Xiao Qiang");Super.Modifyhandshake(SEC, request, response); }@Bean     PublicServerendpointexporterServerendpointexporter() {//This object said, it seems that only the server is tomcat when the need to configure, specifically I did not study        return New Serverendpointexporter(); }}
      1. Only the above configuration is definitely null, as for the reason, the online statement is different, I am not sure, the solution is as follows
    /*** Listener class: The main task is to carry our httpsession in the past with ServletRequest. * @authorHou Yefei */@Component //This note should never be forgotten, its main function is to include this listener in the spring container for management, equivalent to register monitoring it@Slf4j Public classRequestlistenerImplementsServletrequestlistener {@Override       Public void requestinitialized(Servletrequestevent SRE) {//Bring all request requests to the HttpSessionHttpSession session = ((HttpServletRequest) SRE.getservletrequest()).getsession(); Log.Info("Bring all request requests on httpsession {}", session.getId()); } Public Requestlistener() {}@Override       Public void requestdestroyed(Servletrequestevent arg0) {}  }
  4. Also in my Google process there is a blog mention need to add a weblistener annotation, the results found based on springboot words, if not add also does not affect

GitHub Project Address: Demo

The above code is purely personal research, if there is the wrong place, you can leave messages or email!

Preliminary study on Springboot-websocket-getting httpsession problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.