Spring configures WebSocket and enables mass/individual send messages __web

Source: Internet
Author: User
Tags session id sessions
The spring framework has a websocket jar package that enables docking with WebSocket in H5, and even websocket can work with HTTP requests through dependency injection, which is implemented in detail as follows

The file directory structure is as follows, mainly controller and WebSocket folders


1. Configure Automatic Scan loading:

<!--If you use annotations, you only need the following configuration-->
<!--component Scan-->
<context:component-scan base-package= " Com.xiaoxiaohei.ssm.websocket,com.xiaoxiaohei.ssm.controller "></context:component-scan>
<!-- Annotations are loaded automatically without the need to configure the Mapper and adapter-->
<mvc:annotation-driven validator= "Validator" ></mvc:annotation-driven>

2. Create a WebSocket configuration class (which can also be implemented using a configuration file) to implement an interface to configure the path and interceptor for the WebSocket request.

@Configuration
@EnableWebSocket Public
class Websocketconfig implements Websocketconfigurer {

    @Override Public
    void Registerwebsockethandlers (Websockethandlerregistry registry) {
        Registry.addhandler MyHandler ( ), "/myhandler"). Addinterceptors (New Websocketinterceptor ());

    @Bean public
    Websockethandler MyHandler () {return
        new MyHandler ();
    }

}

3. Interceptor is mainly used for user login identification (USERID) record, easy to get the specified user's session identity and send a message to the specified user, in the following interceptor, I get the session ID in the sessions (this identity is setattribute in when logging in, As the following code says, you can also pass H5 in the new WebSocket (URL), pass the identification parameter in the URL, and pass Serverhttprequest.getservletrequest (). Getparametermap () To get the identity information.

public class Websocketinterceptor implements Handshakeinterceptor {@Override public boolean is Forehandshake (serverhttprequest request, serverhttpresponse response, Websockethandler handler, map<string, Object > map) throws Exception {if (Request instanceof Servletserverhttprequest) {Servletserverhttpreque
            St ServerHTTPRequest = (servletserverhttprequest) request;
HttpSession session = Serverhttprequest.getservletrequest (). GetSession ();
Map Parametermap = Serverhttprequest.getservletrequest (). Getparametermap ();
            System.out.println (PARAMETERMAP);
            if (session!= null) {map.put ("UserId", Session.getattribute ("userId"));
    } return true; @Override public void Afterhandshake (ServerHTTPRequest serverhttprequest, Serverhttpresponse serverhttpresponse , Websockethandler Websockethandler, Exception e) {}} 

4. Implement websocket to establish a connection, send a message, disconnect, and so on processing class.

A. After the afterconnectionestablished connection has been successfully established, record the user's connection ID and make it easy to post information, here I record the ID in the map collection.

B. The Send method of H5 WebSocket can be processed in Handletextmessage

C.sendmessagetouser sends a message to the specified user, passing in the user identity and message body

D.sendmessagetoallusers broadcast messages to the left and right users, requiring only incoming message bodies

E.handletransporterror connection error handling, mainly to close the connection of the error session, and delete the records in the Map collection

The f.afterconnectionclosed connection is closed and the records in the map collection are removed.

G.getclientid my own encapsulation of a method to facilitate access to user identification

@Service public class MyHandler extends Textwebsockethandler {//Online user list private static final Map<integer, WEBSO
    Cketsession> users;

    User identity private static final String client_id = "UserId";
    static {users = new hashmap<> (); @Override public void Afterconnectionestablished (Websocketsession session) throws Exception {System.ou
        T.PRINTLN ("Successful establishment of the connection");
        Integer userId = Getclientid (session);
        System.out.println (USERID);
            if (userId!= null) {Users.put (userId, session);
            Session.sendmessage ("Successfully establish socket Connection") (new TextMessage);
            System.out.println (USERID);
        SYSTEM.OUT.PRINTLN (session);
        @Override public void Handletextmessage (websocketsession sessions, TextMessage message) {//...

        System.out.println (Message.getpayload ());
        Websocketmessage message1 = new TextMessage ("Server:" +message); try {session.sendMessage (MESSAGE1);
        catch (IOException e) {e.printstacktrace (); /** * Send information to the specified user * @param clientId * @param message * @return/public boolean S
        Endmessagetouser (Integer clientId, TextMessage message) {if (Users.get (clientId) = null) return false;
        Websocketsession session = Users.get (CLIENTID);
        System.out.println ("SendMessage:" + Session);
        if (!session.isopen ()) return false;
        try {session.sendmessage (message);
            catch (IOException e) {e.printstacktrace ();
        return false;
    return true; /** * Broadcast Information * @param message * @return/public boolean sendmessagetoallusers (textmessage m
        Essage) {Boolean allsendsuccess = true;
        set<integer> clientids = Users.keyset ();
        Websocketsession session = NULL;
  for (Integer clientid:clientids) {try {              Session = Users.get (CLIENTID);
                if (Session.isopen ()) {session.sendmessage (message);
                } catch (IOException e) {e.printstacktrace ();
            Allsendsuccess = false;
    } return allsendsuccess;
        @Override public void Handletransporterror (websocketsession session, Throwable exception) throws exception {
        if (Session.isopen ()) {session.close ();
        } System.out.println ("Connection error");
    Users.remove (Getclientid (session));
        @Override public void Afterconnectionclosed (websocketsession session, Closestatus status) throws Exception {
        SYSTEM.OUT.PRINTLN ("Connection closed:" + status);
    Users.remove (Getclientid (session));
    @Override public boolean supportspartialmessages () {return false; /** * Get User ID * @param session * @return/private IntegerGetclientid (websocketsession session) {try {integer clientId = (integer) session.getattributes (). Get
            (client_id);
        return clientId;
        catch (Exception e) {return null; }
    }
}

1. Can establish a controller for user login, send message, etc. (here need to send a message, just need to use dependency injection)

@Controller public
class Socketcontroller {

    @Autowired
    MyHandler handler;


    @RequestMapping ("/login/{userid}") public
    @ResponseBody String Login (HttpSession session, @PathVariable ("UserId Integer userId) {
        System.out.println ("Login interface, userid=" +userid);
        Session.setattribute ("UserId", userId);
        System.out.println (Session.getattribute ("userId"));

        Return "Success";
    }

    @RequestMapping ("/message") public
    @ResponseBody String SendMessage () {
        Boolean hassend = Handler.sendmessagetouser (4, New TextMessage ("Send a small XI"));
        System.out.println (hassend);
        return ' message ';
    }

}

2. Specific HTML code:

<script type= "Text/javascript" >
  $ (function () {
    console.log ("abc");
    $.ajax ({url: "HTTP://LOCALHOST:8080/LOGIN/4", success:function (Result) {
      console.log (result);
      var ws = new WebSocket ("Ws://localhost:8080/myhandler")
       Ws.onopen = function () {
        console.log ("Onpen");
       Ws.send ("{}");
       }
       Ws.onclose = function () {
        console.log ("OnClose");
       }

      Ws.onmessage = function (msg) {
        console.log (msg.data);
       }
}}) </script>

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.