【转】SpringMVC整合websocket实现消息推送及触发
1.创建websocket握手协议的后台
(1)HandShake的实现类
- /**
- *Project Name: price
- *File Name: HandShake.java
- *Package Name: com.yun.websocket
- *Date: 2016年9月3日 下午4:44:27
- *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
- */
- package com.yun.websocket;
- import java.util.Map;
- import org.springframework.http.server.ServerHttpRequest;
- import org.springframework.http.server.ServerHttpResponse;
- import org.springframework.http.server.ServletServerHttpRequest;
- import org.springframework.web.socket.WebSocketHandler;
- import org.springframework.web.socket.server.HandshakeInterceptor;
- /**
- *Title: HandShake<br/>
- *Description:
- *@Company: 青岛励图高科<br/>
- *@author: 刘云生
- *@version: v1.0
- *@since: JDK 1.7.0_80
- *@Date: 2016年9月3日 下午4:44:27 <br/>
- */
- public class HandShake implements HandshakeInterceptor{
- @Override
- public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Map<String, Object> attributes) throws Exception {
- // TODO Auto-generated method stub
- String jspCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("jspCode");
- // 标记用户
- //String userId = (String) session.getAttribute("userId");
- if(jspCode!=null){
- attributes.put("jspCode", jspCode);
- }else{
- return false;
- }
- return true;
- }
- @Override
- public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Exception exception) {
- // TODO Auto-generated method stub
- }
- }
(2)MyWebSocketConfig的实现类
- /**
- *Project Name: price
- *File Name: MyWebSocketConfig.java
- *Package Name: com.yun.websocket
- *Date: 2016年9月3日 下午4:52:29
- *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
- */
- package com.yun.websocket;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import org.springframework.web.socket.config.annotation.EnableWebSocket;
- import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
- import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
- /**
- *Title: MyWebSocketConfig<br/>
- *Description:
- *@Company: 青岛励图高科<br/>
- *@author: 刘云生
- *@version: v1.0
- *@since: JDK 1.7.0_80
- *@Date: 2016年9月3日 下午4:52:29 <br/>
- */
- @Component
- @EnableWebMvc
- @EnableWebSocket
- public class MyWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
- @Resource
- MyWebSocketHandler handler;
- @Override
- public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
- // TODO Auto-generated method stub
- registry.addHandler(handler, "/wsMy").addInterceptors(new HandShake());
- registry.addHandler(handler, "/wsMy/sockjs").addInterceptors(new HandShake()).withSockJS();
- }
- }
(3)MyWebSocketHandler的实现类
- /**
- *Project Name: price
- *File Name: MyWebSocketHandler.java
- *Package Name: com.yun.websocket
- *Date: 2016年9月3日 下午4:55:12
- *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
- */
- package com.yun.websocket;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import org.springframework.stereotype.Component;
- import org.springframework.web.socket.CloseStatus;
- import org.springframework.web.socket.TextMessage;
- import org.springframework.web.socket.WebSocketHandler;
- import org.springframework.web.socket.WebSocketMessage;
- import org.springframework.web.socket.WebSocketSession;
- import com.google.gson.GsonBuilder;
- /**
- *Title: MyWebSocketHandler<br/>
- *Description:
- *@Company: 青岛励图高科<br/>
- *@author: 刘云生
- *@version: v1.0
- *@since: JDK 1.7.0_80
- *@Date: 2016年9月3日 下午4:55:12 <br/>
- */
- @Component
- public class MyWebSocketHandler implements WebSocketHandler{
- public static final Map<String, WebSocketSession> userSocketSessionMap;
- static {
- userSocketSessionMap = new HashMap<String, WebSocketSession>();
- }
- @Override
- public void afterConnectionEstablished(WebSocketSession session) throws Exception {
- // TODO Auto-generated method stub
- String jspCode = (String) session.getHandshakeAttributes().get("jspCode");
- if (userSocketSessionMap.get(jspCode) == null) {
- userSocketSessionMap.put(jspCode, session);
- }
- for(int i=0;i<10;i++){
- //broadcast(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
- session.sendMessage(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
- }
- }
- @Override
- public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
- // TODO Auto-generated method stub
- //Message msg=new Gson().fromJson(message.getPayload().toString(),Message.class);
- //msg.setDate(new Date());
- // sendMessageToUser(msg.getTo(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
- session.sendMessage(message);
- }
- @Override
- public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
- // TODO Auto-generated method stub
- if (session.isOpen()) {
- session.close();
- }
- Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
- .entrySet().iterator();
- // 移除Socket会话
- while (it.hasNext()) {
- Entry<String, WebSocketSession> entry = it.next();
- if (entry.getValue().getId().equals(session.getId())) {
- userSocketSessionMap.remove(entry.getKey());
- System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
- break;
- }
- }
- }
- @Override
- public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
- // TODO Auto-generated method stub
- System.out.println("Websocket:" + session.getId() + "已经关闭");
- Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
- .entrySet().iterator();
- // 移除Socket会话
- while (it.hasNext()) {
- Entry<String, WebSocketSession> entry = it.next();
- if (entry.getValue().getId().equals(session.getId())) {
- userSocketSessionMap.remove(entry.getKey());
- System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
- break;
- }
- }
- }
- @Override
- public boolean supportsPartialMessages() {
- // TODO Auto-generated method stub
- return false;
- }
- /**
- * 群发
- * @Title: broadcast
- * @Description: TODO
- * @param: @param message
- * @param: @throws IOException
- * @return: void
- * @author: 刘云生
- * @Date: 2016年9月10日 下午4:23:30
- * @throws
- */
- public void broadcast(final TextMessage message) throws IOException {
- Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
- .entrySet().iterator();
- // 多线程群发
- while (it.hasNext()) {
- final Entry<String, WebSocketSession> entry = it.next();
- if (entry.getValue().isOpen()) {
- new Thread(new Runnable() {
- public void run() {
- try {
- if (entry.getValue().isOpen()) {
- entry.getValue().sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
- }
- /**
- * 给所有在线用户的实时工程检测页面发送消息
- *
- * @param message
- * @throws IOException
- */
- public void sendMessageToJsp(final TextMessage message,String type) throws IOException {
- Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
- .entrySet().iterator();
- // 多线程群发
- while (it.hasNext()) {
- final Entry<String, WebSocketSession> entry = it.next();
- if (entry.getValue().isOpen() && entry.getKey().contains(type)) {
- new Thread(new Runnable() {
- public void run() {
- try {
- if (entry.getValue().isOpen()) {
- entry.getValue().sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
- }
- }
2.创建websocket握手处理的前台
- <script>
- var path = '<%=basePath%>';
- var userId = 'lys';
- if(userId==-1){
- window.location.href="<%=basePath2%>";
- }
- var jspCode = userId+"_AAA";
- var websocket;
- if ('WebSocket' in window) {
- websocket = new WebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
- } else if ('MozWebSocket' in window) {
- websocket = new MozWebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
- } else {
- websocket = new SockJS("http://" + path + "wsMy/sockjs?jspCode=" + jspCode);
- }
- websocket.onopen = function(event) {
- console.log("WebSocket:已连接");
- console.log(event);
- };
- websocket.onmessage = function(event) {
- var data = JSON.parse(event.data);
- console.log("WebSocket:收到一条消息-norm", data);
- alert("WebSocket:收到一条消息");
- };
- websocket.onerror = function(event) {
- console.log("WebSocket:发生错误 ");
- console.log(event);
- };
- websocket.onclose = function(event) {
- console.log("WebSocket:已关闭");
- console.log(event);
- }
- </script>
3.通过Controller调用进行websocket的后台推送
- /**
- *Project Name: price
- *File Name: GarlicPriceController.java
- *Package Name: com.yun.price.garlic.controller
- *Date: 2016年6月23日 下午3:23:46
- *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
- */
- package com.yun.price.garlic.controller;
- import java.io.IOException;
- import java.util.Date;
- import java.util.List;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.socket.TextMessage;
- import com.google.gson.GsonBuilder;
- import com.yun.common.entity.DataGrid;
- import com.yun.price.garlic.dao.entity.GarlicPrice;
- import com.yun.price.garlic.model.GarlicPriceModel;
- import com.yun.price.garlic.service.GarlicPriceService;
- import com.yun.websocket.MyWebSocketHandler;
- /**
- * Title: GarlicPriceController<br/>
- * Description:
- *
- * @Company: 青岛励图高科<br/>
- * @author: 刘云生
- * @version: v1.0
- * @since: JDK 1.7.0_80
- * @Date: 2016年6月23日 下午3:23:46 <br/>
- */
- @Controller
- public class GarlicPriceController {
- @Resource
- MyWebSocketHandler myWebSocketHandler;
- @RequestMapping(value = "GarlicPriceController/testWebSocket", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8")
- @ResponseBody
- public String testWebSocket() throws IOException{
- myWebSocketHandler.sendMessageToJsp(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+"GarlicPriceController/testWebSocket"+"\"")), "AAA");
- return "1";
- }
- }
4.所用到的jar包
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-websocket</artifactId>
- <version>4.0.1.RELEASE</version>
- </dependency>
5.运行的环境
【转】SpringMVC整合websocket实现消息推送及触发的更多相关文章
- 在Spring Boot框架下使用WebSocket实现消息推送
Spring Boot的学习持续进行中.前面两篇博客我们介绍了如何使用Spring Boot容器搭建Web项目(使用Spring Boot开发Web项目)以及怎样为我们的Project添加HTTPS的 ...
- WebSocket与消息推送
B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...
- HTML5 学习总结(五)——WebSocket与消息推送
B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...
- HTML5 学习笔记(五)——WebSocket与消息推送
B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...
- 使用websocket进行消息推送服务
Websocket主要做消息推送,简单,轻巧,比comet好用 入门了解:https://www.cnblogs.com/xdp-gacl/p/5193279.html /** * A Web Soc ...
- 实现websocket 主动消息推送,用laravel+Swoole
近来有个需求:想实现一个可以主动触发消息推送的功能,这个可以实现向模板消息那个,给予所有成员发送自定义消息,而不需要通过客户端发送消息,服务端上message中监听传送的消息进行做相对于的业务逻辑. ...
- laravel整合workerman做消息推送系统
官方建议分离 workerman和mvc框架的结合,我去,这不是有点脑缺氧吗? 大量的业务逻辑,去独立增加方法和类库在写一次,实际业务中是不现实和不实际的 gateway增加一些这方面的工作,但是我看 ...
- WebSocket 学习教程(二):Spring websocket实现消息推送
=============================================== 环境介绍: Jdk 1.7 (1.6不支持) Tomcat7.0.52 (支持Websocket协议) ...
- 用图解&&实例讲解php是如何实现websocket实时消息推送的
WebSocket是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. 以前的推送技术使用 Ajax 轮询,浏览器需要不断地向服务器发送http请求来获取最新的数据,浪费很多的带 ...
随机推荐
- sparksql笔记
1.sparksql是Spark用来处理结构化数据的一个模块,它提供了两个抽象DataFrame和DataSet并且作为分布式SQL查询引擎的作用. Hive SQL转换成MapReduce然后提交到 ...
- testNG之顺序执行
@Test testNG1.java: import org.testng.annotations.Test; public class testNG1 { @Test public void t ...
- jdbc baseDAO 以及 每个类的继承
首先是baseDAO,用来作为DAO的父类 package dao; import java.lang.reflect.Field; import java.sql.Connection; impor ...
- (转)使用OpenGL显示图像(六)响应触摸事件
响应触摸事件 编写:jdneo - 原文:http://developer.android.com/training/graphics/opengl/touch.html 让对象根据预设的程序运动(如 ...
- PHP生成PDF完美支持中文,解决TCPDF乱码
PHP生成PDF完美支持中文,解决TCPDF乱码 2011-09-26 09:04 418人阅读 评论(0) 收藏 举报 phpfontsheaderttfxhtml文档 PHP生成PDF完美支持中文 ...
- 6、基于highcharts实现的线性拟合,计算部分在java中实现,画的是正态概率图
1.坐标点类 package cn.test.domain; public class Point { double x; double y; public Point(){ } public Poi ...
- MySQL高级学习笔记(二):mysql配置文件、mysql的用户与权限管理、mysql的一些杂项配置
文章目录 mysql配置文件 二进制日志log-bin 错误日志log-error 数据文件 两系统 Myisam存放方式 innodb存放方式 如何配置 mysql的用户与权限管理 MySQL的用户 ...
- Linux应急响应基础
文件排查 敏感目录文件分析 tmp目录 命令目录 /usr/bin /usr/sbin 开机启动项 /etc/init.d /etc/init.d是/etc/rc.d/init.d的软链接 文件时间 ...
- vue事件修饰符(once:prev:stop)
vue事件修饰符(once:prev:stop) stop修饰符 效果如下: 当你鼠标在这个div里的时候,x与y的值:会随着鼠标的变化而变化.但是当鼠标放在stopMoving的时候,x与y的值是 ...
- Cocos2d-x之项目结构分析
| 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.下面是我们创建cocos2d的工程MyGame01里的文件资源 2. 在下面:文件解决方案下面有6个项目,我们的启动优先项为MyGam ...