• 欢迎访问露水湾网站,WordPress信息,WordPress教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站
  • Git主题现已支持滚动公告栏功能,兼容其他浏览器,看到的就是咯,在后台最新消息那里用li标签添加即可。
  • 最新版Git主题已支持说说碎语功能,可像添加文章一样直接添加说说,新建说说页面即可,最后重新保存固定连接,

spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

编程语言 dewbay 3年前 (2017-05-15) 338次浏览 已收录 0个评论 扫描二维码

spring4.0 以后加入了对websocket技术的支持,撸主目前的项目用的是 SSM(springMVC+spring+MyBatis)框

架,所以肯定要首选spring自带的websocket了,好,现在问题来了,撸主在网上各种狂搜猛找,拼凑了几个自称是

spring websocket的东东,下来一看,废物,其中包括从 github 上 down 下来的。举个例子,在搭建过程中有个问题,

撸主上谷歌搜索,总共搜出来三页结果共 30 条左右,前 15 条是纯英文的  后 15 条是韩语和日语,而这 30 条结果都不能

解决撸主的问题,无奈,只好上官网看全英帮助,在撸主惊人的毅力和不懈奋斗下,纠结了两天的spring+websocket

整合今天算是彻底搭建成功,摸索透彻了。

websocket是目前唯一真正实现全双工通信的服务器向客户端推的互联网技术,与长连接和轮询技术相比,

websocket的优越性不言自明,长连接的连接资源(线程资源)随着连接数量的增多,必会耗尽,客户端轮询会给服

务器造成很大的压力,而 websocket 是在物理层非网络层建立一条客户端至服务器的长连接,以此来保证服务器向客

户端的即时推送,既不耗费线程资源,又不会不断向服务器轮询请求。

下面言归正传,讲一讲撸主在 SSM(springMVC+spring+MyBatis)框架中集成 websocket 技术的曲折蛋疼直至成功喜悦之路。

  • 1 在 maven 的 pom.xml 中加入 websocket 所依赖的 jar 包,什么,你不知道 maven,快去度之或者查看撸主关于 maven 的博文恶补一下,spring-websocket 所依赖的 jar 包有以下几个:
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. <dependency>
  2.     <groupId>javax.servlet</groupId>
  3.     <artifactId>javax.servlet-api</artifactId>
  4.     <version>3.1.0</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>com.fasterxml.jackson.core</groupId>
  8.     <artifactId>jackson-core</artifactId>
  9.     <version>2.3.0</version>
  10. </dependency>
  11. <dependency>
  12.     <groupId>com.fasterxml.jackson.core</groupId>
  13.     <artifactId>jackson-databind</artifactId>
  14.     <version>2.3.0</version>
  15. </dependency>
  16. <dependency>
  17.    <groupId>org.springframework</groupId>
  18.    <artifactId>spring-websocket</artifactId>
  19.    <version>4.0.1.RELEASE</version>
  20. </dependency>
  21. <dependency>
  22.    <groupId>org.springframework</groupId>
  23.    <artifactId>spring-messaging</artifactId>
  24.    <version>4.0.1.RELEASE</version>
  25. </dependency>
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. <beans xmlns=http://www.springframework.org/schema/beans&#8221;
  2.        xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;
  3.        xmlns:websocket=http://www.springframework.org/schema/websocket&#8221;
  4.        xsi:schemaLocation=”
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6.         http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd”>
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. <dependency>
  2. <span style=“white-space:pre”>    </span><groupId>org.springframework</groupId>
  3.     <artifactId>spring-core</artifactId>
  4.     <version>${spring.version}</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>org.springframework</groupId>
  8.     <artifactId>spring-web</artifactId>
  9.     <version>${spring.version}</version>
  10. </dependency>
  11. <dependency>
  12.     <groupId>org.springframework</groupId>
  13.     <artifactId>spring-webmvc</artifactId>
  14.     <version>${spring.version}</version>
  15. </dependency>
  16. <dependency>
  17.     <groupId>org.springframework</groupId>
  18.     <artifactId>spring-context-support</artifactId>
  19.     <version>${spring.version}</version>
  20. </dependency>
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. package com.up.websocket.handler;
  2. import org.springframework.web.socket.TextMessage;
  3. import org.springframework.web.socket.WebSocketSession;
  4. import org.springframework.web.socket.handler.TextWebSocketHandler;
  5. public class WebsocketEndPoint extends TextWebSocketHandler {
  6.     @Override
  7.     protected void handleTextMessage(WebSocketSession session,
  8.             TextMessage message) throws Exception {
  9.         super.handleTextMessage(session, message);
  10.         TextMessage returnMessage = new TextMessage(message.getPayload()+” received at server”);
  11.         session.sendMessage(returnMessage);
  12.     }
  13. }
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. package com.up.websocket;
  2. import java.util.Map;
  3. import org.springframework.http.server.ServerHttpRequest;
  4. import org.springframework.http.server.ServerHttpResponse;
  5. import org.springframework.web.socket.WebSocketHandler;
  6. import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
  7. public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
  8.     @Override
  9.     public boolean beforeHandshake(ServerHttpRequest request,
  10.             ServerHttpResponse response, WebSocketHandler wsHandler,
  11.             Map<String, Object> attributes) throws Exception {
  12.         System.out.println(“Before Handshake”);
  13.         return super.beforeHandshake(request, response, wsHandler, attributes);
  14.     }
  15.     @Override
  16.     public void afterHandshake(ServerHttpRequest request,
  17.             ServerHttpResponse response, WebSocketHandler wsHandler,
  18.             Exception ex) {
  19.         System.out.println(“After Handshake”);
  20.         super.afterHandshake(request, response, wsHandler, ex);
  21.     }
  22. }

 

[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. <bean id=“websocket” class=“com.up.websocket.handler.WebsocketEndPoint”/>
  2. <websocket:handlers>
  3.     <websocket:mapping path=“/websocket” handler=“websocket”/>
  4.     <websocket:handshake-interceptors>
  5.     <bean class=“com.up.websocket.HandshakeInterceptor”/>
  6.     </websocket:handshake-interceptors>
  7. </websocket:handlers>
[html] view plain copy

 spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat’s echo sample)</title>
  5.     <style type=“text/css”>
  6.         #connect-container {
  7.             float: left;
  8.             width: 400px
  9.         }
  10.         #connect-container div {
  11.             padding: 5px;
  12.         }
  13.         #console-container {
  14.             float: left;
  15.             margin-left: 15px;
  16.             width: 400px;
  17.         }
  18.         #console {
  19.             border: 1px solid #CCCCCC;
  20.             border-right-color: #999999;
  21.             border-bottom-color: #999999;
  22.             height: 170px;
  23.             overflow-y: scroll;
  24.             padding: 5px;
  25.             width: 100%;
  26.         }
  27.         #console p {
  28.             padding: 0;
  29.             margin: 0;
  30.         }
  31.     </style>
  32.     <script src=http://cdn.sockjs.org/sockjs-0.3.min.js&#8221;></script>
  33.     <script type=“text/javascript”>
  34.         var ws = null;
  35.         var url = null;
  36.         var transports = [];
  37.         function setConnected(connected) {
  38.             document.getElementById(‘connect’).disabled = connected;
  39.             document.getElementById(‘disconnect’).disabled = !connected;
  40.             document.getElementById(‘echo’).disabled = !connected;
  41.         }
  42.         function connect() {
  43.             alert(“url:”+url);
  44.             if (!url) {
  45.                 alert(‘Select whether to use W3C WebSocket or SockJS’);
  46.                 return;
  47.             }
  48.             ws = (url.indexOf(‘sockjs’) != -1) ?
  49.                 new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);
  50.             ws.onopen = function () {
  51.                 setConnected(true);
  52.                 log(‘Info: connection opened.’);
  53.             };
  54.             ws.onmessage = function (event) {
  55.                 log(‘Received: ‘ + event.data);
  56.             };
  57.             ws.onclose = function (event) {
  58.                 setConnected(false);
  59.                 log(‘Info: connection closed.’);
  60.                 log(event);
  61.             };
  62.         }
  63.         function disconnect() {
  64.             if (ws != null) {
  65.                 ws.close();
  66.                 ws = null;
  67.             }
  68.             setConnected(false);
  69.         }
  70.         function echo() {
  71.             if (ws != null) {
  72.                 var message = document.getElementById(‘message’).value;
  73.                 log(‘Sent: ‘ + message);
  74.                 ws.send(message);
  75.             } else {
  76.                 alert(‘connection not established, please connect.’);
  77.             }
  78.         }
  79.         function updateUrl(urlPath) {
  80.             if (urlPath.indexOf(‘sockjs’) != -1) {
  81.                 url = urlPath;
  82.                 document.getElementById(‘sockJsTransportSelect’).style.visibility = ‘visible’;
  83.             }
  84.             else {
  85.               if (window.location.protocol == ‘http:’) {
  86.                   url = ‘ws://’ + window.location.host + urlPath;
  87.               } else {
  88.                   url = ‘wss://’ + window.location.host + urlPath;
  89.               }
  90.               document.getElementById(‘sockJsTransportSelect’).style.visibility = ‘hidden’;
  91.             }
  92.         }
  93.         function updateTransport(transport) {
  94.             alert(transport);
  95.           transports = (transport == ‘all’) ?  [] : [transport];
  96.         }
  97.         function log(message) {
  98.             var console = document.getElementById(‘console’);
  99.             var p = document.createElement(‘p’);
  100.             p.style.wordWrap = ‘break-word’;
  101.             p.appendChild(document.createTextNode(message));
  102.             console.appendChild(p);
  103.             while (console.childNodes.length > 25) {
  104.                 console.removeChild(console.firstChild);
  105.             }
  106.             console.scrollTop = console.scrollHeight;
  107.         }
  108.     </script>
  109. </head>
  110. <body>
  111. <noscript><h2 style=“color: #ff0000”>Seems your browser doesn’t support Javascript! Websockets
  112.     rely on Javascript being enabled. Please enable
  113.     Javascript and reload this page!</h2></noscript>
  114. <div>
  115.     <div id=“connect-container”>
  116.         <input id=“radio1” type=“radio” name=“group1” onclick=“updateUrl(”/spring-websocket-uptest/websocket’);”>
  117.             <label for=“radio1”>W3C WebSocket</label>
  118.         <br>
  119.         <input id=“radio2” type=“radio” name=“group1” onclick=“updateUrl(‘/spring-websocket-uptest/websocket’);”>
  120.             <label for=“radio2”>SockJS</label>
  121.         <div id=“sockJsTransportSelect” style=“visibility:hidden;”>
  122.             <span>SockJS transport:</span>
  123.             <select onchange=“updateTransport(this.value)”>
  124.               <option value=“all”>all</option>
  125.               <option value=“websocket”>websocket</option>
  126.               <option value=“xhr-polling”>xhr-polling</option>
  127.               <option value=“jsonp-polling”>jsonp-polling</option>
  128.               <option value=“xhr-streaming”>xhr-streaming</option>
  129.               <option value=“iframe-eventsource”>iframe-eventsource</option>
  130.               <option value=“iframe-htmlfile”>iframe-htmlfile</option>
  131.             </select>
  132.         </div>
  133.         <div>
  134.             <button id=“connect” onclick=“connect();”>Connect</button>
  135.             <button id=“disconnect” disabled=“disabled” onclick=“disconnect();”>Disconnect</button>
  136.         </div>
  137.         <div>
  138.             <textarea id=“message” style=“width: 350px”>Here is a message!</textarea>
  139.         </div>
  140.         <div>
  141.             <button id=“echo” onclick=“echo();” disabled=“disabled”>Echo message</button>
  142.         </div>
  143.     </div>
  144.     <div id=“console-container”>
  145.         <div id=“console”></div>
  146.     </div>
  147. </div>
  148. </body>
  149. </html>
尊重原创,转载请注明出处:http://blog.csdn.net/gisredevelopment/article/details/38392629


露水湾 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)
喜欢 (0)
[]
分享 (0)
关于作者:
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址