【转】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的Class类、"this."关键字、Constructor构造器(一)
import java.util.*; public class BookTest { public static void main(String[] args) { //Book book = n ...
- 20150127 学军集训 day1
day1 就直接考试... 和说好的不一样啊 第一题看都没怎么看就pass了,构造的题我一向没什么把握.然后瞟到第三题有30分可做,虽然要写的代码很大...反正我是写习惯了..期间纠结了一会还写了一个 ...
- apue 第10章 信号signal
每种信号都有名字,都是以SIG开头 信号机制最简单的接口是signal函数 #include <signal.h> typedef void (*sighandler_t)(int); s ...
- MySQL主从同步(binlog方式)
原文:https://blog.csdn.net/demonson/article/details/80526533
- Tomcat负载均衡图片显示不正常解决方法
在部署一个Tomcat玩玩的时候,发现在做nginx负载均衡时,网站显示不正常,图片会变得很大.测试了半天都没成功,最后查找资料,才发现Tomcat负载均衡时Session处理有问题,Session是 ...
- layui多图上传加隐藏域
我的情况是,通过layui上传图片调用后端,后端将图片上传后返回图片路径,上传成功后将图片在页面显示出来(避免用户网速不稳定,图片其实还没上传成功就进行下一步操作),然后同步每个图片增加隐藏域,最终表 ...
- 在ios微信中提交form,php端收不到参数的问题
今天做h5页面时,微信浏览器中提交form表单,发现php端收不到post过来的参数,在普通浏览器中可以,安卓微信也可以,$_POST,$_GET,$_REQUEST等方式都不行. 后来,把form表 ...
- 探索Redis设计与实现2:Redis内部数据结构详解——dict
本文转自互联网 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial ...
- leetcode上的一些动态规划
70-爬楼梯 思路:该问题可以理解为经典的“斐波那契数列”问题,但这里需要用动规实现,递归会超时 class Solution { public: int climbStairs(int n) { v ...
- 洛谷 P2024 [NOI2001]食物链——带权值的并查集维护
先上一波题目 https://www.luogu.org/problem/P2024 通过这道题复习了一波并查集,学习了一波带权值操作 首先我们观察到 所有的环都是以A->B->C-> ...