Springmvc+WebSocket整合
WebSocket是为解决客户端与服务端实时通信而产生的技术。其本质是先通过HTTP/HTTPS协议进行握手后创建一个用于交换数据的TCP连接,此后服务端与客户端通过此TCP连接进行实时通信。
以前我们实现推送技术,用的都是轮询,在特点的时间间隔有浏览器自动发出请求,将服务器的消息主动的拉回来,在这种情况下,我们需要不断的向服务器 发送请求,然而HTTP request 的header是非常长的,里面包含的数据可能只是一个很小的值,这样会占用很多的带宽和服务器资源。会占用大量的带宽和服务器资源。
WebSocket 最伟大之处在于服务器和客户端可以在给定的时间范围内的任意时刻,相互推送信息。在建立连接之后,服务器可以主动传送数据给客户端。此外,服务器与客户端之间交换的标头信息很小。
WebSocket并不限于以Ajax(或XHR)方式通信,因为Ajax技术需要客户端发起请求,而WebSocket服务器和客户端可以彼此相互推送信息。
如何使用?
注意:spring4.0以后加入了对websocket技术的支持,base项目的spring版本为3.1.4,升到4.0.2后加入spring自带的websocket包。
1、maven pom.xml加入websocket所依赖的jar包
<!-- websocket -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</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、在servlet-context中添加
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd
3、创建websocket的处理类
handleTextMessage
消息处理方法,接收会话中前端发送给后台的message,再通过sendMessage发送到前端
afterConnectionEstablished 连接建立后处理方法
afterConnectionClosed 连接关闭后处理方法
package cn.com.bmsoft.base.websocket;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import cn.com.bmsoft.base.service.face.management.IGasService;
import cn.com.bmsoft.base.service.face.management.IHomeMonitorService;
import cn.com.bmsoft.base.service.face.management.IInfraredService;
@RequestMapping("websocket")
public class WebsocketEndPoint extends TextWebSocketHandler {
@Autowired
IHomeMonitorService homeMonitorService;
@Autowired
IGasService gasService;
@Autowired
IInfraredService infraredService;
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
super.handleTextMessage(session, message);
String phonemessage = message.getPayload();
session.sendMessage(message);
}
@Override
public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);
System.out.println("Connection Establied!");
newScheduledThreadPool.scheduleWithFixedDelay(new TimerTask() {
public void run() {
try {
Map<String, Object> queryParams = new HashMap<String, Object>();
queryParams.put("gStatus","1");
queryParams.put("iStatus","1");
//查询未通知异常条数
int gwarns = gasService.count(queryParams);
int iwarns = infraredService.count(queryParams);
if((gwarns+iwarns)!=0){
session.sendMessage(new TextMessage((gwarns+iwarns)+""));
}else{
session.sendMessage(new TextMessage(0+""));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 5000, TimeUnit.MILLISECONDS);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("Connection Closed!");
}
}
4、创建握手协议
package cn.com.bmsoft.base.websocket;
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;
import java.util.Map;
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
5、servletcontext配置处理类和握手协议
<!-- spring-websocket配置start-->
<bean id="websocket" class="cn.com.bmsoft.base.websocket.WebsocketEndPoint" />
<websocket:handlers>
<websocket:mapping path="/websocket" handler="websocket" />
<websocket:handshake-interceptors>
<bean class="cn.com.bmsoft.base.websocket.HandshakeInterceptor" />
</websocket:handshake-interceptors>
</websocket:handlers>
<!-- spring-websocket配置end-->
6、客户端页面
<!DOCTYPE html>
<html>
<head>
<title>websocket example</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=8,9,10" />
<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" src="${requestContext.contextPath}/resources/scripts/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 = new WebSocket(url); //申请一个WebSocket对象
ws.onopen = function () {
setConnected(true);
log('Info: connection opened.');
};
ws.onmessage = function (event) {
//var msgJson=eval("("+event.data+")");
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);
var msg = '"frdId":"'+28+'",'
+ '"content":"'
+ message + '"';
ws.send(msg);
// ws.send(message);
} else {
alert('connection not established, please connect.');
}
}
function updateUrl(urlPath) {
if (window.location.protocol == 'http:') {
url = 'ws://' + window.location.host + urlPath;
} else {
url = 'wss://' + window.location.host + urlPath;
}
}
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>
<script type="text/javascript" src="${requestContext.contextPath}/resources/scripts/jquery-${jqueryVersion}.min.js"></script>
<script type="text/javascript">
$(function(){
//移除顶端遮罩
if (top.hideMask) top.hideMask();
});
</script>
<body>
<div>
<div id="connect-container">
<input id="radio1" type="radio" name="group1" onclick="updateUrl('/base/websocket');">
<label for="radio1">W3C WebSocket</label>
<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>
sockjs-0.3.min.js
链接:http://pan.baidu.com/s/1c2uLpDY 密码:5zxh
Springmvc+WebSocket整合的更多相关文章
- spring+websocket整合
java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序: Apach Tomcat 8.0.3+MyEclipse+maven+JD ...
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- SpringMVC+redis整合
在网络上有一个很多人转载的springmvc+redis整合的案例,不过一直不完整,也是被各种人装来转去,现在基本将该框架搭建起来. package com.pudp.bae.base; import ...
- sonne_game网站开发03 spring-mvc+freemarker整合
今天的任务就是在spring+mybatis+springmvc的基础上,将freemarker整合进来. freemarker是什么? freemarker是一种模板引擎.它的目的是基于模板和数据, ...
- SpringMVC 中整合之JSON、XML
每次看到好的博客我就想好好的整理起来,便于后面自己复习,同时也共享给网络上的伙伴们! 博客地址: springMVC整合Jaxb2.xStream: http://www.cnblogs.com/h ...
- 框架篇:Spring+SpringMVC+hibernate整合开发
前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...
- IDEA下使用maven构建web项目(SpringMVC+Mybatis整合)
需求背景:由于最近总是接到一些需求,需要配合前端团队快速建设移动端UI应用或web应用及后台业务逻辑支撑的需求,若每次都复用之前复杂业务应用的项目代码,总会携带很多暂时不会用到的功能或组件,这样的初始 ...
- 框架篇:Spring+SpringMVC+Mybatis整合开发
前言: 前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html),然而mybatis表示不服啊. Mybatis:"我抗议!" ...
随机推荐
- SET构造函数
set<int,greater<int>> S; 可以在第二个参数位置设置比较模板,效果和sort类似,less表示升序,greater表示降序.这样做的好处是为了方便应对题目 ...
- BIT-区间修改单点查询
正好刷题时碰到了这个之前遇到过的问题,类似的还有区间修改区间查询,以后学了会补上. 我们知道BIT只支持单点修改区间查询,如果现在问题变成每次让一个区间的数同时变化,然后询问的是某一个点得值的时候该怎 ...
- Echarts 简单报表系列四:雷达图
代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- Hadoop---HDFS读写流程
Hadoop---HDFS HDFS 性能详解 HDFS 天生是为大规模数据存储与计算服务的,而对大规模数据的处理目前还有没比较稳妥的解决方案. HDFS 将将要存储的大文件进行分割,分割到既定的存储 ...
- SQLServer 2008以上误操作数据库恢复方法—日志尾部备份
原文出处:http://blog.csdn.net/dba_huangzj/article/details/8491327 问题: 经常看到有人误删数据,或者误操作,特别是update和delete的 ...
- CP-ABE的使用
参考: http://acsc.cs.utexas.edu/cpabe/tutorial.html http://acsc.cs.utexas.edu/cpabe/ 事先先配置好cp-abe:http ...
- 检测用户命令序列异常——使用LSTM分类算法【使用朴素贝叶斯,类似垃圾邮件分类的做法也可以,将命令序列看成是垃圾邮件】
通过 搜集 Linux 服务器 的 bash 操作 日志, 通过 训练 识别 出 特定 用户 的 操作 习惯, 然后 进一步 识别 出 异常 操作 行为. 使用 SEA 数据 集 涵盖 70 多个 U ...
- git rebase commit 信息处理
pick:正常选中 reword:选中,并且修改提交信息: edit:选中,rebase时会暂停,允许你修改这个commit(参考这里) squash:选中,会将当前commit与上一个commit合 ...
- @RequestParam的使用
来源:http://825635381.iteye.com/blog/2196911 @RequestParam: 一. 基本使用,获取提交的参数 后端代码: @RequestMapping(&quo ...
- 把旧系统迁移到.Net Core 2.0 日记(10) -- EF core 和之前版本多对多映射区别
EF Core 现在不支持多对多映射,只能做2个一对多映射. 比如Product和Category 我现在定义Product和Category是多对多关系. 那么实体定义如下: public clas ...