spring+websocket整合(springMVC+spring+MyBatis即SSM框架和

Car65M 8年前發布 | 84K 次閱讀 WebSocket 開發

來自: http://blog.csdn.net/heng_ji/article/details/39007227


java-websocket的搭建非常之容易,沒用框架的童鞋可以在這里下載擼主親自調教好的java-websocket程序:

Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7

http://download.csdn.net/detail/up19910522/7719087


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 在CODE上查看代碼片 派生到我的代碼片
  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>  
  • 2 更新web.xml中namespace.xsd的版本,

[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:websocket="http://www.springframework.org/schema/websocket"  
  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">  
  • 3 更新spring框架的jar包至4.0以上(spring-core, spring-context, spring-web and spring-webmvc)

[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
  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>  
  • 4  4.1創建websocket處理類

[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
  1. package com.up.websocket.handler;  
  2.   
  3. import org.springframework.web.socket.TextMessage;  
  4. import org.springframework.web.socket.WebSocketSession;  
  5. import org.springframework.web.socket.handler.TextWebSocketHandler;  
  6.   
  7. public class WebsocketEndPoint extends TextWebSocketHandler {  
  8.   
  9.     @Override  
  10.     protected void handleTextMessage(WebSocketSession session,  
  11.             TextMessage message) throws Exception {  
  12.         super.handleTextMessage(session, message);  
  13.         TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
  14.         session.sendMessage(returnMessage);  
  15.     }  
  16. }  
  • 4.2創建握手(handshake)接口

[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
  1. package com.up.websocket;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import org.springframework.http.server.ServerHttpRequest;  
  6. import org.springframework.http.server.ServerHttpResponse;  
  7. import org.springframework.web.socket.WebSocketHandler;  
  8. import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;  
  9.   
  10. public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{  
  11.   
  12.     @Override  
  13.     public boolean beforeHandshake(ServerHttpRequest request,  
  14.             ServerHttpResponse response, WebSocketHandler wsHandler,  
  15.             Map<String, Object> attributes) throws Exception {  
  16.         System.out.println("Before Handshake");  
  17.         return super.beforeHandshake(request, response, wsHandler, attributes);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void afterHandshake(ServerHttpRequest request,  
  22.             ServerHttpResponse response, WebSocketHandler wsHandler,  
  23.             Exception ex) {  
  24.         System.out.println("After Handshake");  
  25.         super.afterHandshake(request, response, wsHandler, ex);  
  26.     }  
  27.   
  28. }  

  • 5 處理類和握手協議的spring配置(applicationContext.xml文件)

[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
  1. <bean id="websocket" class="com.up.websocket.handler.WebsocketEndPoint"/>  
  2.   
  3. <websocket:handlers>  
  4.     <websocket:mapping path="/websocket" handler="websocket"/>  
  5.     <websocket:handshake-interceptors>  
  6.     <bean class="com.up.websocket.HandshakeInterceptor"/>  
  7.     </websocket:handshake-interceptors>  
  8. </websocket:handlers>  


  • 6 客戶端頁面

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


  • 7  按照以上步驟搭建,根據個人開發環境不同,可能會出現各種問題,下面將在整個搭建過程中遇到的問題總結一下,詳見博文:http://blog.csdn.net/gisredevelopment/article/details/38397569
 本文由用戶 Car65M 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!