spring+websocket綜合(springMVC+spring+MyBatis這是SSM框架和websocket集成技術)

java-websocket該建築是easy。兒童無用的框架能夠在這裏下載主線和我的教學好java-websocket計劃:javascript

Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7css

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


spring4.0之後增長了對websocket技術的支持,擼主眼下的項目用的是SSM(springMVC+spring+MyBatis)框java

架,所以確定要首選spring自帶的websocket了,好,現在問題來了,擼主在網上各類狂搜猛找,拼湊了幾個自稱git

spring websocket的東東。下來一看,廢物。當中包含從github上down下來的。舉個樣例。在搭建過程當中有個問題,github

擼主上谷歌搜索,總共搜出來三頁結果共30條左右,前15條是純英文的  後15條是韓語和日語,而這30條結果都不能web

解決擼主的問題,無奈,僅僅好上官網看全英幫助,在擼主驚人的毅力和不懈奮鬥下。糾結了兩天的spring+websocketspring

整合今天算是完全搭建成功,摸索透徹了。json

websocket是眼下惟一真正實現全雙工通訊的server向client推的互聯網技術,與長鏈接和輪詢技術相比,api

websocket的優越性不言自明,長鏈接的鏈接資源(線程資源)隨着鏈接數量的增多。必會耗盡。client輪詢會給服

務器形成很是大的壓力,而websocket是在物理層非網絡層創建一條client至server的長鏈接,以此來保證server向客

戶端的即時推送,既不耗費線程資源,又不會不斷向server輪詢請求。

如下言歸正傳,講一講擼主在SSM(springMVC+spring+MyBatis)框架中集成websocket技術的曲折蛋疼直至成功喜悅之路。

  • 1 在maven的pom.xml中增長websocket所依賴的jar包,什麼,你不知道maven,快去度之或者查看擼主關於maven的博文惡補一下,spring-websocket所依賴的jar包有下面幾個:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
   <version>4.0.1.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-messaging</artifactId>
   <version>4.0.1.RELEASE</version>
</dependency>

  • 2 更新web.xml中namespace.xsd的版本號。

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:websocket="http://www.springframework.org/schema/websocket"
	   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">

  • 3 更新spring框架的jar包至4.0以上(spring-core, spring-context, spring-web and spring-webmvc)

<dependency>
<span style="white-space:pre">	</span><groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>${spring.version}</version>
</dependency>

  • 4  4.1建立websocket處理類

package com.up.websocket.handler;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class WebsocketEndPoint extends TextWebSocketHandler {

	@Override
	protected void handleTextMessage(WebSocketSession session,
			TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
		session.sendMessage(returnMessage);
	}
}

  • 4.2建立握手(handshake)接口

package com.up.websocket;

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;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		System.out.println("Before Handshake");
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		System.out.println("After Handshake");
		super.afterHandshake(request, response, wsHandler, ex);
	}

}

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

<bean id="websocket" class="com.up.websocket.handler.WebsocketEndPoint"/>

<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket"/>
    <websocket:handshake-interceptors>
    <bean class="com.up.websocket.HandshakeInterceptor"/>
    </websocket:handshake-interceptors>
</websocket:handlers>


  • 6 client頁面

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title>
    <style type="text/css">
        #connect-container {
            float: left;
            width: 400px
        }

        #connect-container div {
            padding: 5px;
        }

        #console-container {
            float: left;
            margin-left: 15px;
            width: 400px;
        }

        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }

        #console p {
            padding: 0;
            margin: 0;
        }
    </style>

    <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>

    <script type="text/javascript">
        var ws = null;
        var url = null;
        var transports = [];

        function setConnected(connected) {
            document.getElementById('connect').disabled = connected;
            document.getElementById('disconnect').disabled = !connected;
            document.getElementById('echo').disabled = !connected;
        }

        function connect() {
        	alert("url:"+url);
            if (!url) {
                alert('Select whether to use W3C WebSocket or SockJS');
                return;
            }

            ws = (url.indexOf('sockjs') != -1) ?

new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url); ws.onopen = function () { setConnected(true); log('Info: connection opened.'); }; ws.onmessage = function (event) { log('Received: ' + event.data); }; ws.onclose = function (event) { setConnected(false); log('Info: connection closed.'); log(event); }; } function disconnect() { if (ws != null) { ws.close(); ws = null; } setConnected(false); } function echo() { if (ws != null) { var message = document.getElementById('message').value; log('Sent: ' + message); ws.send(message); } else { alert('connection not established, please connect.'); } } function updateUrl(urlPath) { if (urlPath.indexOf('sockjs') != -1) { url = urlPath; document.getElementById('sockJsTransportSelect').style.visibility = 'visible'; } else { if (window.location.protocol == 'http:') { url = 'ws://' + window.location.host + urlPath; } else { url = 'wss://' + window.location.host + urlPath; } document.getElementById('sockJsTransportSelect').style.visibility = 'hidden'; } } function updateTransport(transport) { alert(transport); transports = (transport == 'all') ? [] : [transport]; } function log(message) { var console = document.getElementById('console'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.appendChild(document.createTextNode(message)); console.appendChild(p); while (console.childNodes.length > 25) { console.removeChild(console.firstChild); } console.scrollTop = console.scrollHeight; } </script> </head> <body> <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable Javascript and reload this page!</h2></noscript> <div> <div id="connect-container"> <input id="radio1" type="radio" name="group1" onclick="updateUrl(''/spring-websocket-uptest/websocket');"> <label for="radio1">W3C WebSocket</label> <br> <input id="radio2" type="radio" name="group1" onclick="updateUrl('/spring-websocket-uptest/websocket');"> <label for="radio2">SockJS</label> <div id="sockJsTransportSelect" style="visibility:hidden;"> <span>SockJS transport:</span> <select onchange="updateTransport(this.value)"> <option value="all">all</option> <option value="websocket">websocket</option> <option value="xhr-polling">xhr-polling</option> <option value="jsonp-polling">jsonp-polling</option> <option value="xhr-streaming">xhr-streaming</option> <option value="iframe-eventsource">iframe-eventsource</option> <option value="iframe-htmlfile">iframe-htmlfile</option> </select> </div> <div> <button id="connect" onclick="connect();">Connect</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button> </div> <div> <textarea id="message" style="width: 350px">Here is a message!</textarea> </div> <div> <button id="echo" onclick="echo();" disabled="disabled">Echo message</button> </div> </div> <div id="console-container"> <div id="console"></div> </div> </div> </body> </html>


  • 7  依照以上步驟搭建,依據我的開發環境不一樣。可能會出現各類問題,如下將在整個搭建過程當中遇到的問題總結一下,詳見博文:http://blog.csdn.net/gisredevelopment/article/details/38397569



演示實例加強版下載:spring-websocket-uptest.rar

尊重原創。轉載請註明出處:

http://blog.csdn.net/gisredevelopment/article/details/38392629


技術郵箱,免費答疑:897658573@qq.com
相關文章
相關標籤/搜索