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

spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)纠结了两天的

大家好,又见面了,我是你们的朋友全栈君。

———————20170612更新——————————–

很多小伙伴反映原来的工程无法下载,这个锅得CSDN背,可能下载量达到一定程度就涉嫌违规了吧。现给出GitHub地址,增强简化配置版的demo,可能跟下文讲的不完全匹配,但原理是一样的,只不过省去了配置而改用注解。

Git JavaWebSocket地址,尽量star一下哦,不定期增强更新功能。

——————-我是阔爱的分割线——————————–

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

<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 客户端页面

<!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" οnclick="updateUrl(''/spring-websocket-uptest/websocket');">
            <label for="radio1">W3C WebSocket</label>
        <br>
        <input id="radio2" type="radio" name="group1" οnclick="updateUrl('/spring-websocket-uptest/websocket');">
            <label for="radio2">SockJS</label>
        <div id="sockJsTransportSelect" style="visibility:hidden;">
            <span>SockJS transport:</span>
            <select οnchange="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" οnclick="connect();">Connect</button>
            <button id="disconnect" disabled="disabled" οnclick="disconnect();">Disconnect</button>
        </div>
        <div>
            <textarea id="message" style="width: 350px">Here is a message!</textarea>
        </div>
        <div>
            <button id="echo" οnclick="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

尊重原创,转载请注明出处:

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/157296.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 实战篇-OpenSSL之AES加密算法-CFB1模式

    本文属于《OpenSSL加密算法库使用系列教程》之一,欢迎查看其它文章。实战篇-OpenSSL之AES加密算法-CFB1模式一、AES简介二、CFB1模式1、命令行操作2、函数说明3、编程实现(1)特别注意(2)实现CFB1模式加解密(3)测试代码一、AES简介密码学中的高级加密标准(AdvancedEncryptionStandard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程

    2022年4月9日
    123
  • synchronousqueue场景_java中SynchronousQueue的核心方法

    synchronousqueue场景_java中SynchronousQueue的核心方法我们之前提过SynchronousQueue入队和出队的两种方法,其实它们都依托transfer方法得以实现。相比较而言,transfer可以同步进行入队和出队的操作,是SynchronousQueue中最重要的核心方法。下面我们就transfer概念、使用场景,以及在代码中增减元素的实例带来全面介绍。1.transfer概念进行匹配交换数据,SynchronousQueue内部使用Transfe…

    2022年6月22日
    45
  • WAR包补丁工具_修改war包配置文件

    WAR包补丁工具_修改war包配置文件简要:因目前处于运维历史悠久的WEB项目中,每次需求开发完成需要更打补丁文件,因此编写打补丁工具,以解决手动查找补丁文件的繁琐且重复操作。纯Java代码编写,使用Swing作为界面UI,原有代码只针对特殊使用场景,可以适当加以修改。适用:编译工具:EclipseLunaRelease(4.4.0)运行环境:JDK1.7代码:界面GUI部分:使用JSplitPane…

    2022年10月5日
    0
  • vip导致的serverConnection closed by foreign host问题

    vip导致的serverConnection closed by foreign host问题问题描述:应应用需求,设计搭建了一套带tokudb存储引擎的percona数据库,使用的是常见的双主架构。具体的架构如下图所示:在172.20.32.x1上进行验证的时候出现了下面的问题:FHo

    2022年7月2日
    27
  • Java 构造函数特点「建议收藏」

    Java 构造函数特点「建议收藏」(1).一般函数是用于定义对象应该具备的功能。而构造函数定义的是,对象在调用功能之前,在建立时,应该具备的一些内容。也就是对象的初始化内容。(2).构造函数是在对象建立时由jvm调用,给对象初始化。一般函数是对象建立后,当对象调用该功能时才会执行。(3).普通函数可以使用对象多次调用,构造函数就在创建对象时调用。(4).构造函数的函数名要与类名一样,而普通的函数只要符合标识符的命名…

    2022年6月17日
    18
  • win10 设定计划任务时提示所指定的账户名称无效,如何解决?「建议收藏」

    win10 设定计划任务时提示所指定的账户名称无效,如何解决?「建议收藏」我想把我的python爬虫脚本设定为自动定时执行,我的设备是win10操作系统,这将用到系统自带的计划任务功能。且我希望不管用户是否登录都要运行该定时任务,但在设置计划任务的属性时,遇到一个报错:所指定的账户名称无效。该报错是如何发生的,以及如何解决?记录如下:报错是如何发生的?如下图所示,设置计划任务的属性:如果仅勾选“只在用户登录时运行”,点击“确定”后直接创建成功。…

    2022年6月10日
    129

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号