首页 > 程序开发 > 软件开发 > Java >

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

2014-08-07

java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序: Apach Tomcat 8 0 3+MyEclipse+maven+JDK1 7 spring4 0以后加入了对websocket技术的支持,撸主目前的项

java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序:

Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7

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包有以下几个:


    javax.servlet
    javax.servlet-api
    3.1.0


    com.fasterxml.jackson.core
    jackson-core
    2.3.0


    com.fasterxml.jackson.core
    jackson-databind
    2.3.0


   org.springframework
   spring-websocket
   4.0.1.RELEASE


   org.springframework
   spring-messaging
   4.0.1.RELEASE

2 更新web.xml中namespace.xsd的版本,

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


	org.springframework
	spring-core
	${spring.version}


	org.springframework
	spring-web
	${spring.version}


	org.springframework
	spring-webmvc
	${spring.version}


	org.springframework
	spring-context-support
	${spring.version}

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 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文件)




    
    
    
    

6 客户端页面




<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(&#39;connect&#39;).disabled = connected;
            document.getElementById(&#39;disconnect&#39;).disabled = !connected;
            document.getElementById(&#39;echo&#39;).disabled = !connected;
        }

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

            ws = (url.indexOf(&#39;sockjs&#39;) != -1) ? 
                new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);

            ws.onopen = function () {
                setConnected(true);
                log(&#39;Info: connection opened.&#39;);
            };
            ws.onmessage = function (event) {
                log(&#39;Received: &#39; + event.data);
            };
            ws.onclose = function (event) {
                setConnected(false);
                log(&#39;Info: connection closed.&#39;);
                log(event);
            };
        }

        function disconnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
            setConnected(false);
        }

        function echo() {
            if (ws != null) {
                var message = document.getElementById(&#39;message&#39;).value;
                log(&#39;Sent: &#39; + message);
                ws.send(message);
            } else {
                alert(&#39;connection not established, please connect.&#39;);
            }
        }

        function updateUrl(urlPath) {
            if (urlPath.indexOf(&#39;sockjs&#39;) != -1) {
                url = urlPath;
                document.getElementById(&#39;sockJsTransportSelect&#39;).style.visibility = &#39;visible&#39;;
            }
            else {
              if (window.location.protocol == &#39;http:&#39;) {
                  url = &#39;ws://&#39; + window.location.host + urlPath;
              } else {
                  url = &#39;wss://&#39; + window.location.host + urlPath;
              }
              document.getElementById(&#39;sockJsTransportSelect&#39;).style.visibility = &#39;hidden&#39;;
            }
        }

        function updateTransport(transport) {
        	alert(transport);
          transports = (transport == &#39;all&#39;) ?  [] : [transport];
        }
        
        function log(message) {
            var console = document.getElementById(&#39;console&#39;);
            var p = document.createElement(&#39;p&#39;);
            p.style.wordWrap = &#39;break-word&#39;;
            p.appendChild(document.createTextNode(message));
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        }
    </script>

7 按照以上步骤搭建,根据个人开发环境不同,可能会出现各种问题,下面将在整个搭建过程中遇到的问题总结一下,详见博文:http://blog.csdn.net/gisredevelopment/article/details/38397569




相关文章
最新文章
热点推荐