【转】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请求来获取最新的数据,浪费很多的带 ...
随机推荐
- vue 路由动态传参 (多个)
动态传参 传值页面 客户列表clientList.vue 路由 router.js 配置路由 接收参数的页面 客户详情CustomerDetails.vue 通过this.$router.para ...
- linux shell的单行多行注释
1.单行注释,使用符号# echo " echo "test" #echo "comment“ 2. 多行注释 (1)使用 :<<! ! file ...
- 【Flutter学习】页面跳转之SliverAppBar,CustomScrollView,NestedScrollView的使用
一,flutter SliverAppbar 控件介绍 SliverAppBar “应用栏” 相当于升级版的 appbar 于 AppBar 位置的固定的应用最上面的; 而 SliverAppBar ...
- Comet OJ 三元组 推导+两个指针+分类讨论
题目:https://www.cometoj.com/contest/59/problem/F?problem_id=2681 题意:给你n个三元组 ai,bi,ci,如果某一对三元组满足 2* ...
- error C4996: 'stricmp': The POSIX name for this item is deprecated
转自VC错误:http://www.vcerror.com/?p=164 问题描述: 最近使用了VS2012,在使用 stricmp和ltoa函数的时候,报出了以下错误信息 error C4996: ...
- shell 删除除匹配字符串之外的所有文件夹
file_dir=` -maxdepth - type d`for dir in $file_dirdo file_name=`basename $dir` if [ $file_name != &q ...
- 2.5 Nginx服务器基础配置实例
pay平台nginx配置文件详解 ###全局块### user www www; #指定运行worker process 的用户和用户组 worker_processes 4; #指定Nginx开 ...
- 快速调通支付宝当面付Demo
1.访问如下地址: https://auth.alipay.com/login/ant_sso_index.htm?goto=https%3A%2F%2Fopenhome.alipay.com%2Fp ...
- HBase优化——读写优化
Hbase2.0查询优化 1)设置scan缓存 HBase中Scan查询可以设置缓存,方法是setCaching(),这样可以有效的减少服务端与客户端的交互,更有效的提升扫描查询的性能. Scan s ...
- tonight i need your body
wdnmd wdnmd 再lable中我们有几个不同的type参数: text 写的是文本类型的参数 password 不管输入的是什么显示的都是星星 date 输入的是一个日历本 ...