【转】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请求来获取最新的数据,浪费很多的带 ...
随机推荐
- java--ArrayList,LinkedList应用比较
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListDem ...
- Docker部署Flask应用
创建应用 首先,编写一个简单的Flask应用:docker_test/flask_app.py Docker 安装 请根据自己的操作系统自行安装. Docker简介 Docker 镜像 Docker镜 ...
- 【leetcode】989. Add to Array-Form of Integer
题目如下: For a non-negative integer X, the array-form of X is an array of its digits in left to right o ...
- python 学习 -- 第一天 初涉
久闻python大名却一直没去了解,趁学校培训这个机会 开始正式学习python 第一天初步介绍一点关于python的东西 安装了环境及编译器 环境是在之前就安装了 只安装编译器anaconda 之后 ...
- express框架总结
1.express教程及api : http://www.runoob.com/nodejs/nodejs-express-framework.html 2.nodejs的express自动生成项目框 ...
- 一些idea
二分答案似乎和最小生成树有着不可描述的奇怪关系.(滑稽 联赛级别的在矩形上乱搞的题无非几个思路(按出现概率排序):建图,二维前缀和,dp 涉及到求合法区间数的问题往往要用到桶.等差数列等思想,或者尝试 ...
- videojs 播放无法通过URI确定格式的视频源(flv/mp4)
前言 前人坑我千百遍我待前人如初恋.最近公司开源节流搬机房,需要把原来的服务迁移,然后屁颠屁颠的把一个跑了几年没人管的视频网站(知道这个网站的人都走了)迁移到新的机房去. 结果跑起来发现原来里面同时存 ...
- webpack构建缓存机制-hash介绍
前言 浏览器为了优化体验,会有缓存机制.如果浏览器判断当前资源没有更新,就不会去服务端下载,而是直接使用本地资源.在webpack的构建中,我们通常使用给文件添加后缀值来改名以及提取公共代码到不会改变 ...
- (4)C++ 复合类型-指针
篇幅长从 https://www.cnblogs.com/buchizaodian/p/11511256.html 提取出来 七.指针和自由存储空间 1.寻址运算符 * #include<io ...
- 79、tensorflow计算一个五层神经网络的正则化损失系数、防止网络过拟合、正则化的思想就是在损失函数中加入刻画模型复杂程度的指标
''' Created on Apr 20, 2017 @author: P0079482 ''' import tensorflow as tf #获取一层神经网络边上的权重,并将这个权重的L2正则 ...