【转】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请求来获取最新的数据,浪费很多的带 ...
随机推荐
- pipeline语法之environment,dir(),deleteDir()方法,readJSON,writeJSON
一 environment指令指定一系列键值对,这些对值将被定义为所有步骤的环境变量或阶段特定步骤 environment{…}, 大括号里面写一些键值对,也就是定义一些变量并赋值,这些变量就是环境变 ...
- JSON和fastjson
一.JSON 语法规则: 数据在名称/值对中 数据由逗号分隔 花括号保存对象 方括号保存数组 名称/值对-->对象-->数组 JSON 名称/值对 JSON 数据的书写格式是:名称/值对. ...
- 【leetcode】990. Satisfiability of Equality Equations
题目如下: Given an array equations of strings that represent relationships between variables, each strin ...
- FastDFSClient上传图片工具类
package cn.lijun.core.util; import org.apache.commons.io.FilenameUtils;import org.csource.common.Nam ...
- PHP curl_multi_select函数
curl_multi_select — 等待所有cURL批处理中的活动连接 说明 int curl_multi_select ( resource $mh [, float $timeout = 1. ...
- POJ 3414 Pots (dfs,这个代码好长啊QAQ)
Description You are given two pots, having the volume of A and B liters respectively. The following ...
- 【dart学习】之字典(Map)的相关方法总结
一,概述 通常来讲,Map是一个键值对相关的对象,键和值可以是任何类型的对象.每个键只出现一次,而一个值则可以出现多次.映射是动态集合. 换句话说,Maps可以在运行时增长和缩小. dart:core ...
- 【Flutter学习】页面跳转之路由及导航
一,概述 移动应用通常通过成为‘屏幕’或者‘页面’的全屏元素显示其内容,在Flutter中,这些元素统称为路由,它们由导航器Navigator组件管理.导航器管理一组路由Route对象,并提供了管理堆 ...
- SqlServer2008跨服务器操作
--创建链接服务器 exec sp_addlinkedserver @server= 'SQL2' --链接服务器名 , @srvproduct= '' --OLE DB 数据源的产品名称:如果为 S ...
- linux基础知识汇总(二)-vi/vim
转:http://blog.csdn.net/sky04/article/details/5662582 vi与vim一样都是编辑器,不同的是vim更高级一些,可以理解是vi的高级版本.vi就像Win ...