2019独角兽企业重金招聘Python工程师标准>>>

1.创建websocket握手协议的后台

(1)HandShake的实现类

[java] view plain copy

  1. /**
  2. *Project Name: price
  3. *File Name:    HandShake.java
  4. *Package Name: com.yun.websocket
  5. *Date:         2016年9月3日 下午4:44:27
  6. *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
  7. */
  8. package com.yun.websocket;
  9. import java.util.Map;
  10. import org.springframework.http.server.ServerHttpRequest;
  11. import org.springframework.http.server.ServerHttpResponse;
  12. import org.springframework.http.server.ServletServerHttpRequest;
  13. import org.springframework.web.socket.WebSocketHandler;
  14. import org.springframework.web.socket.server.HandshakeInterceptor;
  15. /**
  16. *Title:      HandShake<br/>
  17. *Description:
  18. *@Company:   青岛励图高科<br/>
  19. *@author:    刘云生
  20. *@version:   v1.0
  21. *@since:     JDK 1.7.0_80
  22. *@Date:      2016年9月3日 下午4:44:27 <br/>
  23. */
  24. public class HandShake implements HandshakeInterceptor{
  25. @Override
  26. public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  27. Map<String, Object> attributes) throws Exception {
  28. // TODO Auto-generated method stub
  29. String jspCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("jspCode");
  30. // 标记用户
  31. //String userId = (String) session.getAttribute("userId");
  32. if(jspCode!=null){
  33. attributes.put("jspCode", jspCode);
  34. }else{
  35. return false;
  36. }
  37. return true;
  38. }
  39. @Override
  40. public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  41. Exception exception) {
  42. // TODO Auto-generated method stub
  43. }
  44. }

(2)MyWebSocketConfig的实现类

[java] view plain copy

  1. /**
  2. *Project Name: price
  3. *File Name:    MyWebSocketConfig.java
  4. *Package Name: com.yun.websocket
  5. *Date:         2016年9月3日 下午4:52:29
  6. *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
  7. */
  8. package com.yun.websocket;
  9. import javax.annotation.Resource;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  12. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  13. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  14. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  15. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  16. /**
  17. *Title:      MyWebSocketConfig<br/>
  18. *Description:
  19. *@Company:   青岛励图高科<br/>
  20. *@author:    刘云生
  21. *@version:   v1.0
  22. *@since:     JDK 1.7.0_80
  23. *@Date:      2016年9月3日 下午4:52:29 <br/>
  24. */
  25. @Component
  26. @EnableWebMvc
  27. @EnableWebSocket
  28. public class MyWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
  29. @Resource
  30. MyWebSocketHandler handler;
  31. @Override
  32. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  33. // TODO Auto-generated method stub
  34. registry.addHandler(handler, "/wsMy").addInterceptors(new HandShake());
  35. registry.addHandler(handler, "/wsMy/sockjs").addInterceptors(new HandShake()).withSockJS();
  36. }
  37. }

(3)MyWebSocketHandler的实现类

[java] view plain copy

  1. /**
  2. *Project Name: price
  3. *File Name:    MyWebSocketHandler.java
  4. *Package Name: com.yun.websocket
  5. *Date:         2016年9月3日 下午4:55:12
  6. *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
  7. */
  8. package com.yun.websocket;
  9. import java.io.IOException;
  10. import java.util.HashMap;
  11. import java.util.Iterator;
  12. import java.util.Map;
  13. import java.util.Map.Entry;
  14. import org.springframework.stereotype.Component;
  15. import org.springframework.web.socket.CloseStatus;
  16. import org.springframework.web.socket.TextMessage;
  17. import org.springframework.web.socket.WebSocketHandler;
  18. import org.springframework.web.socket.WebSocketMessage;
  19. import org.springframework.web.socket.WebSocketSession;
  20. import com.google.gson.GsonBuilder;
  21. /**
  22. *Title:      MyWebSocketHandler<br/>
  23. *Description:
  24. *@Company:   青岛励图高科<br/>
  25. *@author:    刘云生
  26. *@version:   v1.0
  27. *@since:     JDK 1.7.0_80
  28. *@Date:      2016年9月3日 下午4:55:12 <br/>
  29. */
  30. @Component
  31. public class MyWebSocketHandler implements WebSocketHandler{
  32. public static final Map<String, WebSocketSession> userSocketSessionMap;
  33. static {
  34. userSocketSessionMap = new HashMap<String, WebSocketSession>();
  35. }
  36. @Override
  37. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  38. // TODO Auto-generated method stub
  39. String jspCode = (String) session.getHandshakeAttributes().get("jspCode");
  40. if (userSocketSessionMap.get(jspCode) == null) {
  41. userSocketSessionMap.put(jspCode, session);
  42. }
  43. for(int i=0;i<10;i++){
  44. //broadcast(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
  45. session.sendMessage(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
  46. }
  47. }
  48. @Override
  49. public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
  50. // TODO Auto-generated method stub
  51. //Message msg=new Gson().fromJson(message.getPayload().toString(),Message.class);
  52. //msg.setDate(new Date());
  53. //      sendMessageToUser(msg.getTo(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
  54. session.sendMessage(message);
  55. }
  56. @Override
  57. public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
  58. // TODO Auto-generated method stub
  59. if (session.isOpen()) {
  60. session.close();
  61. }
  62. Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
  63. .entrySet().iterator();
  64. // 移除Socket会话
  65. while (it.hasNext()) {
  66. Entry<String, WebSocketSession> entry = it.next();
  67. if (entry.getValue().getId().equals(session.getId())) {
  68. userSocketSessionMap.remove(entry.getKey());
  69. System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
  70. break;
  71. }
  72. }
  73. }
  74. @Override
  75. public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
  76. // TODO Auto-generated method stub
  77. System.out.println("Websocket:" + session.getId() + "已经关闭");
  78. Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
  79. .entrySet().iterator();
  80. // 移除Socket会话
  81. while (it.hasNext()) {
  82. Entry<String, WebSocketSession> entry = it.next();
  83. if (entry.getValue().getId().equals(session.getId())) {
  84. userSocketSessionMap.remove(entry.getKey());
  85. System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
  86. break;
  87. }
  88. }
  89. }
  90. @Override
  91. public boolean supportsPartialMessages() {
  92. // TODO Auto-generated method stub
  93. return false;
  94. }
  95. /**
  96. * 群发
  97. * @Title:       broadcast
  98. * @Description: TODO
  99. * @param:       @param message
  100. * @param:       @throws IOException
  101. * @return:      void
  102. * @author:      刘云生
  103. * @Date:        2016年9月10日 下午4:23:30
  104. * @throws
  105. */
  106. public void broadcast(final TextMessage message) throws IOException {
  107. Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
  108. .entrySet().iterator();
  109. // 多线程群发
  110. while (it.hasNext()) {
  111. final Entry<String, WebSocketSession> entry = it.next();
  112. if (entry.getValue().isOpen()) {
  113. new Thread(new Runnable() {
  114. public void run() {
  115. try {
  116. if (entry.getValue().isOpen()) {
  117. entry.getValue().sendMessage(message);
  118. }
  119. } catch (IOException e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. }).start();
  124. }
  125. }
  126. }
  127. /**
  128. * 给所有在线用户的实时工程检测页面发送消息
  129. *
  130. * @param message
  131. * @throws IOException
  132. */
  133. public void sendMessageToJsp(final TextMessage message,String type) throws IOException {
  134. Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap
  135. .entrySet().iterator();
  136. // 多线程群发
  137. while (it.hasNext()) {
  138. final Entry<String, WebSocketSession> entry = it.next();
  139. if (entry.getValue().isOpen() && entry.getKey().contains(type)) {
  140. new Thread(new Runnable() {
  141. public void run() {
  142. try {
  143. if (entry.getValue().isOpen()) {
  144. entry.getValue().sendMessage(message);
  145. }
  146. } catch (IOException e) {
  147. e.printStackTrace();
  148. }
  149. }
  150. }).start();
  151. }
  152. }
  153. }
  154. }

2.创建websocket握手处理的前台

[javascript] view plain copy

  1. <script>
  2. var path = '<%=basePath%>';
  3. var userId = 'lys';
  4. if(userId==-1){
  5. window.location.href="<%=basePath2%>";
  6. }
  7. var jspCode = userId+"_AAA";
  8. var websocket;
  9. if ('WebSocket' in window) {
  10. websocket = new WebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
  11. } else if ('MozWebSocket' in window) {
  12. websocket = new MozWebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
  13. } else {
  14. websocket = new SockJS("http://" + path + "wsMy/sockjs?jspCode=" + jspCode);
  15. }
  16. websocket.onopen = function(event) {
  17. console.log("WebSocket:已连接");
  18. console.log(event);
  19. };
  20. websocket.onmessage = function(event) {
  21. var data = JSON.parse(event.data);
  22. console.log("WebSocket:收到一条消息-norm", data);
  23. alert("WebSocket:收到一条消息");
  24. };
  25. websocket.onerror = function(event) {
  26. console.log("WebSocket:发生错误 ");
  27. console.log(event);
  28. };
  29. websocket.onclose = function(event) {
  30. console.log("WebSocket:已关闭");
  31. console.log(event);
  32. }
  33. </script>

3.通过Controller调用进行websocket的后台推送

[java] view plain copy

  1. /**
  2. *Project Name: price
  3. *File Name:    GarlicPriceController.java
  4. *Package Name: com.yun.price.garlic.controller
  5. *Date:         2016年6月23日 下午3:23:46
  6. *Copyright (c) 2016,578888218@qq.com All Rights Reserved.
  7. */
  8. package com.yun.price.garlic.controller;
  9. import java.io.IOException;
  10. import java.util.Date;
  11. import java.util.List;
  12. import javax.annotation.Resource;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpSession;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.stereotype.Controller;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestMethod;
  19. import org.springframework.web.bind.annotation.ResponseBody;
  20. import org.springframework.web.context.request.RequestContextHolder;
  21. import org.springframework.web.context.request.ServletRequestAttributes;
  22. import org.springframework.web.servlet.ModelAndView;
  23. import org.springframework.web.socket.TextMessage;
  24. import com.google.gson.GsonBuilder;
  25. import com.yun.common.entity.DataGrid;
  26. import com.yun.price.garlic.dao.entity.GarlicPrice;
  27. import com.yun.price.garlic.model.GarlicPriceModel;
  28. import com.yun.price.garlic.service.GarlicPriceService;
  29. import com.yun.websocket.MyWebSocketHandler;
  30. /**
  31. * Title: GarlicPriceController<br/>
  32. * Description:
  33. *
  34. * @Company: 青岛励图高科<br/>
  35. * @author: 刘云生
  36. * @version: v1.0
  37. * @since: JDK 1.7.0_80
  38. * @Date: 2016年6月23日 下午3:23:46 <br/>
  39. */
  40. @Controller
  41. public class GarlicPriceController {
  42. @Resource
  43. MyWebSocketHandler myWebSocketHandler;
  44. @RequestMapping(value = "GarlicPriceController/testWebSocket", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8")
  45. @ResponseBody
  46. public String testWebSocket() throws IOException{
  47. myWebSocketHandler.sendMessageToJsp(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+"GarlicPriceController/testWebSocket"+"\"")), "AAA");
  48. return "1";
  49. }
  50. }

4.所用到的jar包

[html] view plain copy

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-websocket</artifactId>
  4. <version>4.0.1.RELEASE</version>
  5. </dependency>

5.运行的环境

至少tomcat8.0以上版本,否则可能报错

原博文:http://blog.csdn.net/liuyunshengsir/article/details/52495919

转载于:https://my.oschina.net/u/3576011/blog/1559057

SpringMVC整合websocket实现消息推送及触发相关推荐

  1. java整合消息推送_SpringMVC整合websocket实现消息推送及触发功能

    本文为大家分享了SpringMVC整合websocket实现消息推送,供大家参考,具体内容如下 1.创建websocket握手协议的后台 (1)HandShake的实现类 /** *Project N ...

  2. springboot定时发送短信_springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送)...

    websocket springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送) 使用WebSocket构建交互式Web应用程序 本指南将引导您完成创建" ...

  3. springboot整合websocket进行消息推送

    什么是websocket? WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据. ...

  4. springboot整合websocket实现消息推送

    springboot整合websocket 1.WebSocket介绍与原理 介绍:WebSocket是HTML5一种新的协议.它实现了浏览器与服务器全双工通信.一开始的握手需要借助HTTP请求完成. ...

  5. php通知websocket,php实现websocket实时消息推送

    php实现websocket实时消息推送,供大家参考,具体内容如下 SocketService.php /** * Created by xwx * Date: 2017/10/18 * Time: ...

  6. python websocket实现消息推送_python Django websocket 实时消息推送

    [实例简介] Django websocket 实时消息推送 服务端主动推送 调用 send(username, title, data, url) username:用户名 title:消息标题 d ...

  7. python websocket实时消息推送

    python websocket实时消息推送 十分想念顺店杂可... 本人写的渣,大神勿喷. 转载请附带本文链接,谢谢. 服务端代码 # -*- coding: utf-8 -*- # @Time : ...

  8. vue-admin websocket接收消息推送+语音提示(详细代码)

    websocket接收消息推送+语音提示 这个是同事的代码,我拿来记录一下,希望以后可以看得懂-- utils/websocket.js const audioUrl = require('@/ass ...

  9. uniapp接收服务器消息,【教程】uniapp websocket实现消息推送

    部分开发者在使用uniapp的过程中会用到websocket,但是uniapp框架提供的websocket服务并不是尽善尽美. 我在这里为大家介绍一款第三方的websocket推送服务:GoEasy, ...

最新文章

  1. 判断tvs能抗住多少千伏浪涌的依据_TVS浪涌保护介绍
  2. 代码自解释不是不写注释的理由
  3. vue php企业站案例,vue 开发企业微信整合案例分析
  4. c++ 一维数组长度_每天一点C / 一维数组和指针
  5. LeNet网络配置文件 lenet_train_test.prototxt
  6. VS中出现 模块计算机类型“x86”与目标计算机类型“x64”冲突
  7. phpexcel如何读和写大于26列的excel
  8. python获取时间秒数_Python获取秒级时间戳与毫秒级时间戳
  9. Dubbo :广播模式下Can't assign requested address问题
  10. Magento网店自定义模板初探(1)——文件夹结构
  11. 雅虎宣布其史上最严重数据泄露:5亿账户于2014年被盗
  12. SpringBoot(30) 整合PageOffice实现在线编辑Word和Excel
  13. python可以ps吗_Python功能确实非常强大!不止PS可以美化照片Python也可以!满分...
  14. c语言生成exe文件,打开exe文件闪退怎么办
  15. Linux CentOS 7中安装XXX(持续更新)
  16. TLS Handshake failed: tls: server selected unsupported protocol version 301
  17. 解决The authenticity of host can’t be established ECDSA key fingerprint is SHA256
  18. 千氪公开课 | 自媒体下半场,如何把握区块链写作的红利?
  19. windows装机必备:文件查找神器Everything + Wox
  20. [POI2011] SEJ-Strongbox(数论)

热门文章

  1. 织梦图集php,dedecms织梦文章模型增加图集功能教程
  2. WIN10 + Tensorflow1.12 + Cmake编译 + Bazel编译
  3. 08:Calling Extraterrestrial Intelligence AgainMOOC程序设计算法基础期末第八题
  4. 洛谷P5282 【模板】快速阶乘算法(多项式多点求值+MTT)
  5. 磊科路由器如何设置虚拟服务器,nw711磊科路由器设置桥接步骤图文
  6. 战队口号霸气押韵8字_衡水中学历届学生最霸气的100条励志标语!条条经典!...
  7. 旧金山大学数据结构和算法的可视化学习工具
  8. 2019/12/24论文小组交流
  9. 这几款摸鱼神器,让我惊了!
  10. [转载] 中华典故故事(孙刚)——26 叫了王承恩