Spring+websocket implementation of Message push

Source: Internet
Author: User

Websocet service-side Implementation

Websocketconfig.java

@Configuration @enablewebmvc@enablewebsocketpublic class Websocketconfig extends Webmvcconfigureradapter implements Websocketconfigurer {    @Override public    void Registerwebsockethandlers (websockethandlerregistry Registry) {        registry.addhandler (systemwebsockethandler (), "/websocketserver"). addinterceptors (new Websockethandshakeinterceptor ());        Registry.addhandler (systemwebsockethandler (), "/sockjs/websocketserver"). addinterceptors (new Websockethandshakeinterceptor ())                . withsockjs ();    }    @Bean public    websockethandler systemwebsockethandler () {        return new Systemwebsockethandler ();}    }
Do not forget to configure an automatic scan of this class in the SPRINGMVC configuration file

<context:component-scan base-package= "com.ldl.origami.websocket"/>

@Configuration

@EnableWebMvc
@EnableWebSocket
The three general meaning is to enable this class to support the @bean load of beans, and support SPRINGMVC and websocket, not very accurate roughly so, try to @EnableWebMvc do not add no effect,@ Configuration supports automatic scanning of SPRINGMVC


Registry.addhandler (systemwebsockethandler (), "/websocketserver"). addinterceptors (new Websockethandshakeinterceptor ())
To register the WebSocket server implementation class, The second parameter is to access the WebSocket address



Registry.addhandler (systemwebsockethandler (), "/sockjs/websocketserver"). addinterceptors (new Websockethandshakeinterceptor ())                . withsockjs ();    }
This is the registration method using Sockjs.


First Systemwebsockethandler.java


public class Systemwebsockethandler implements Websockethandler {private static final Logger Logger;    private static final arraylist<websocketsession> users;        Static {users = new Arraylist<> ();    Logger = Loggerfactory.getlogger (systemwebsockethandler.class);    } @Autowired Private Websocketservice websocketservice; @Override public void afterconnectionestablished (websocketsession Session) throws Exception {logger.debug ("conn        ECT to the WebSocket success ... ");        Users.add (session);        String userName = (string) session.getattributes (). get (constants.websocket_username); If (username!= null) {//query unread message int count = Websocketservice.getunreadnews (String) Session.getattribu            TES (). Get (constants.websocket_username));        Session.sendmessage (new textmessage (count + "")); }} @Override public void handlemessage (websocketsession session, websocketmessage<?> Message) throws ExcEption {//sendmessagetousers ();        } @Override public void Handletransporterror (websocketsession session, throwable Exception) throws Exception {        If (session.isopen ()) {session.close ();        } logger.debug ("websocket Connection closed ...");    Users.remove (session);        } @Override public void afterconnectionclosed (websocketsession session, closestatus Closestatus) throws Exception {        Logger.debug ("websocket Connection closed ...");    Users.remove (session);    } @Override public boolean supportspartialmessages () {return false;        /** * Send message to all online users * * @param message */public void Sendmessagetousers (textmessage Message) { For (websocketsession user:users) {try {if (user.isopen ()) {user.send                Message (message);            }} catch (ioexception e) {e.printstacktrace (); }        }    }    /**     * Send a message to a user * * @param userName * @param message * * public void Sendmessagetouser (String userName, TextMessage message) {for (websocketsession user:users) {if (user.getattributes (). get (constants.web Socket_username). equals (USERNAME)) {try {if (user.isopen ()) {u                    Ser.sendmessage (message);                }} catch (ioexception e) {e.printstacktrace ();            } break; }        }    }}



Related content you can understand it when you see it, it's not much to Explain.


Then Websockethandshakeinterceptor.java


public class Websockethandshakeinterceptor implements Handshakeinterceptor {private static Logger Logger = Loggerfacto    Ry.getlogger (handshakeinterceptor.class); @Override public boolean beforehandshake (serverhttprequest request, serverhttpresponse response, websockethandler wsHa ndler, map<string, Object > Attributes) throws Exception {if (request instanceof Servletserve            Rhttprequest) {servletserverhttprequest servletrequest = (servletserverhttprequest) request;            HttpSession session = Servletrequest.getservletrequest (). getsession (false); If (session! = Null) {//use userName to differentiate Websockethandler so that directed send message String UserName = (string) SE                Ssion.getattribute (constants.session_username);            Attributes.put (constants.websocket_username,username);    }} return true; } @Override public void Afterhandshake (serverhttprequest request, serverhttpresponse response, WEbsockethandler wshandler, Exception Exception) {}} 

the main function of this is to obtain the user name in the current request and save it to the current Websockethandler in order to determine the user of the Websockethandler. specifically, refer to Httpsessionhandshakeinterceptor

User Login Establish WebSocket connection

index.jsp

<script type= "text/javascript" src= "http://localhost            : 8080/origami/websocket/sockjs-0.3.min.js "></script> <script> var websocket;            If (' WebSocket ' in window) {WebSocket = new WebSocket ("ws://localhost:8080/origami/websocketserver"); } else if (' mozwebsocket ' in window) {websocket = new Mozwebsocket ("ws://localhost:8080/origami/we            Bsocketserver ");            } else {websocket = new Sockjs ("http://localhost:8080/Origami/sockjs/webSocketServer");            } Websocket.onopen = function (evnt) {}; Websocket.onmessage = function (evnt) {$ ("#msgcount"). html ("(<font color= ' red ' >" +evnt.data+ "</fon            t>)};            Websocket.onerror = function (evnt) {}; Websocket.onclose = function (evnt) {} </script> 


Be careful when using SOCKJS

1. The wording of these two

<script type= "text/javascript" src= "http://localhost:8080/Origami/websocket/sockjs-0.3.min.js" ></script >
WebSocket = new Sockjs ("http://localhost:8080/Origami/sockjs/webSocketServer");
2. Web. XML
<web-app version= "3.0" xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ Web-app_3_1.xsd ">
Version
Web-app_3_1.xsd
Both of these versions are 3.0+.


And then add it to this servlet.

<async-supported>true</async-supported>


<servlet><servlet-name>appServlet</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> Contextconfiglocation</param-name><param-value>classpath*:servlet-context.xml</param-value> </init-param><load-on-startup>1</load-on-startup>        <async-supported>true</ Async-supported></servlet>

And then all the filter is added

<async-supported>true</async-supported>


3. Add related dependencies

<dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId> jackson-annotations</artifactid>            <version>2.3.0</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId> jackson-core</artifactid>            <version>2.3.1</version>        </dependency>        < dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId> jackson-databind</artifactid>            <version>2.3.3</version>        </dependency>
okay, now WebSocket can build up.



Returns a message that is not read by the user

When the connection is established, it will enter the Systemwebsockethandler afterconnectionestablished method, the code to see the top, remove the websockethandshakeinterceptor saved in the user name

use session.sendmessage (new textmessage (count + ")) to query information, return to user, where to go


service-side push messages to users

@Controllerpublic class Admincontroller {    static Logger Logger = Loggerfactory.getlogger (admincontroller.class);    @Autowired (required = False)    private Adminservice adminservice;    @Bean public    systemwebsockethandler systemwebsockethandler () {        return new Systemwebsockethandler ();    }    @RequestMapping ("/auditing")    @ResponseBody public    String auditing (httpservletrequest request) {        // The extraneous code omits        int unreadnewscount = adminservice.getunreadnews (username);        Systemwebsockethandler (). sendmessagetouser (username, New textmessage (unreadnewscount + ""));        return result;}    }

Here you can use Sendmessagetouser to push messages to a user, or you can use Sendmessagetousers to push messages to all users

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.