Spring 4.x MVC Integration WebSocket and SOCKJS full reference guide (including Nginx/https support) __js

Source: Internet
Author: User
Tags aop

The reason why SOCKJS will exist, not to listen to the point, is because Microsoft is a rogue, now use Windows 7 system is still nearly half, and Windows 7 by default with IE 8, some will automatically update to IE 9, but most non-it users are not willing or will not upgrade (usually we do it to think very simple things, in other industries, it is the Bible, do not feel impossible, the reality has been so).

Now it's time to take a complete look at the Spring 4.x integrated SOCKJS and some additional considerations when running under Tomcat 7.

Spring WebSocket relies on jars:

        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId> javax.websocket-api</artifactid>
            <version>1.1</version>
            <scope>provided</ Scope> <!--Note that scope must be provided, otherwise runtime will conflict, and if Tomcat 8 is used, the Javax.websocket-api.jar under Tomcat_home/lib will also need to be deleted- ->
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.2.8.RELEASE</version>
        </dependency>

You do not need to rely on spring-messaging unless you use the STOMP protocol.

Spring supports WebSocket in two modes, one through the ws://protocol of the native WebSocket specification (individuals who believe that if you determine to use standard websocket access only, you might as well upgrade Tomcat to 8.x (Tomcat 8 native support JSR 356 annotations), Spring's bulk encapsulation adds a lot of extra load, and the other is accessed through SOCKJS (that is, JS), which is temporarily incompatible.

First complete description of:

1, build the spring MVC environment, this assumes the reader is known;

2. The above two jar packages are introduced into the pom.xml;

3. Spring support WebSocket A total of four small steps, handler, Interceptor, Config, and Web.xml, which can basically be considered a replica of spring MVC.

3.1, the creation of websockethandler,spring support two ways, One is to implement the Org.springframework.web.socket.WebSocketHandler interface, the other is to inherit Textwebsockethandler or Binarywebsockethandler (now most of the template framework or plug-in It is usually provided on the basis of the API to provide an abstract class, to put some of the unified work ahead of time, so that applications only need to care about the business, our own company's middleware framework many are also implemented in this mode.

/** * * * * * * Package com.ld.net.spider.demo.ws; /** * @author zhjh256@163.com * {@link} http://www.cnblogs.com/zhjh256/import org.springframework.web.socket.CloseSt
ATUs;
Import Org.springframework.web.socket.TextMessage;
Import Org.springframework.web.socket.WebSocketHandler;
Import Org.springframework.web.socket.WebSocketMessage;

Import org.springframework.web.socket.WebSocketSession; public class Demowshandler implements Websockethandler {@Override public void afterconnectionestablished (W  
        Ebsocketsession session) throws Exception {System.out.println ("Connect to the WebSocket success ...");  
    Session.sendmessage (New TextMessage ("server:connected ok!"));  @Override public void Handlemessage (websocketsession wss, websocketmessage<?> WSM) throws Exception  
        {TextMessage ReturnMessage = new TextMessage (wsm.getpayload () + "received at server"); System.out.println (Wss.gethandshakeheaDERs (). GetFirst ("Cookie"));  
    Wss.sendmessage (ReturnMessage);  
        @Override public void Handletransporterror (websocketsession wss, Throwable thrwbl) throws Exception {  
        if (Wss.isopen ()) {wss.close ();  
    } System.out.println ("WebSocket connection closed ...");  
        @Override public void afterconnectionclosed (websocketsession WSS, Closestatus CS) throws Exception {  
    SYSTEM.OUT.PRINTLN ("WebSocket connection closed ...");  
    @Override public boolean supportspartialmessages () {return false; }
}

3.2, creating interceptors

/** * * * * * * Package com.ld.net.spider.demo.ws;

Import Java.util.Map;
Import Org.springframework.http.server.ServerHttpRequest;
Import Org.springframework.http.server.ServerHttpResponse;
Import Org.springframework.web.socket.WebSocketHandler;

Import Org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; /** * @author zhjh256@163.com * {@link} http://www.cnblogs.com/zhjh256/public class Handshakeinterceptor extends Ht Tpsessionhandshakeinterceptor {@Override public boolean beforehandshake (ServerHTTPRequest request, S  Erverhttpresponse response, Websockethandler Wshandler, map<string, object> attributes) throws Exception {//resolve the extension [x-webkit-deflate-frame] is not supported question if (Request.getheaders (). ContainsKey ("S Ec-websocket-extensions ")) {request.getheaders (). Set (" Sec-websocket-extensions "," permess
        Age-deflate "); } System.out.println ("BeforE handshake ");
    return Super.beforehandshake (Request, response, Wshandler, attributes); @Override public void Afterhandshake (ServerHTTPRequest request, serverhttpresponse response, WEBSOC
        Kethandler Wshandler, Exception ex) {System.out.println ("after handshake");
    Super.afterhandshake (Request, Response, Wshandler, ex); }
}

3.3, Bean configuration

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:p=" http://www.springframework.org/schema/p "xmlns:aop=" http://www.springframework.org/ Schema/aop "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:mvc=" http:// Www.springframework.org/schema/mvc "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:mongo=" http:// Www.springframework.org/schema/data/mongo "xmlns:cache=" Http://www.springframework.org/schema/cache "xmlns:c=" Http://www.springframework.org/schema/c "xmlns:amq=" Http://activemq.apache.org/schema/core "xmlns:websocket=" Http://www.springframework.org/schema/websocket "xmlns:jms=" Http://www.springframework.org/schema/jms "xmlns: Util= "Http://www.springframework.org/schema/util" xsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/ WebSocket Http://www.springframework.org/schema/websocket/spring-websocket.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/ Mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/ Context/spring-context.xsd Http://www.springframework.org/schema/data/mongo http://www.springframework.org/ Schema/data/mongo/spring-mongo-1.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/ Schema/tx/spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd Http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/
Spring-cache.xsd Http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS http://www.springframework.org/schema/jms/spring-jms.xsd http:// Www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> < Websocket:hanDlers allowed-origins= "*" > <websocket:mapping path= "/springws/websocket.ws" handler= "DemoWSHandler"/> <websocket:handshake-interceptors> <bean class= "Com.ld.net.spider.demo.ws.HandshakeInterceptor" /> </websocket:handshake-interceptors> </websocket:handlers> <bean id= "Demowshandler" C lass= "Com.ld.net.spider.demo.ws.DemoWSHandler"/>

Above all, the instructions for 1, spring Javadoc are to allow all sources to access by default, but we run down and find that it's always a 403 error to not configure Allowed-origins.

2, SOCKJS is not allowed to have a suffix, otherwise it will not match, will be specifically mentioned later.

3.4, Web.xml Configuration

Add *.ws mappings to Web.xml (if not/*), as follows:

    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.ws< /url-pattern>
    </servlet-mapping>

Once the above configuration is complete, it can be accessed through the standard WebSocket interface, as shown below.

4, WebSocket Client

<! DOCTYPE html>

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.