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

(1)HandShake的实现类

  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的实现类

  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的实现类

  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握手处理的前台

  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的后台推送

  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包

  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

【转】SpringMVC整合websocket实现消息推送及触发的更多相关文章

  1. 在Spring Boot框架下使用WebSocket实现消息推送

    Spring Boot的学习持续进行中.前面两篇博客我们介绍了如何使用Spring Boot容器搭建Web项目(使用Spring Boot开发Web项目)以及怎样为我们的Project添加HTTPS的 ...

  2. WebSocket与消息推送

    B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...

  3. HTML5 学习总结(五)——WebSocket与消息推送

    B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...

  4. HTML5 学习笔记(五)——WebSocket与消息推送

    B/S结构的软件项目中有时客户端需要实时的获得服务器消息,但默认HTTP协议只支持请求响应模式,这样做可以简化Web服务器,减少服务器的负担,加快响应速度,因为服务器不需要与客户端长时间建立一个通信链 ...

  5. 使用websocket进行消息推送服务

    Websocket主要做消息推送,简单,轻巧,比comet好用 入门了解:https://www.cnblogs.com/xdp-gacl/p/5193279.html /** * A Web Soc ...

  6. 实现websocket 主动消息推送,用laravel+Swoole

    近来有个需求:想实现一个可以主动触发消息推送的功能,这个可以实现向模板消息那个,给予所有成员发送自定义消息,而不需要通过客户端发送消息,服务端上message中监听传送的消息进行做相对于的业务逻辑. ...

  7. laravel整合workerman做消息推送系统

    官方建议分离 workerman和mvc框架的结合,我去,这不是有点脑缺氧吗? 大量的业务逻辑,去独立增加方法和类库在写一次,实际业务中是不现实和不实际的 gateway增加一些这方面的工作,但是我看 ...

  8. WebSocket 学习教程(二):Spring websocket实现消息推送

    =============================================== 环境介绍: Jdk 1.7 (1.6不支持) Tomcat7.0.52 (支持Websocket协议) ...

  9. 用图解&&实例讲解php是如何实现websocket实时消息推送的

    WebSocket是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. 以前的推送技术使用 Ajax 轮询,浏览器需要不断地向服务器发送http请求来获取最新的数据,浪费很多的带 ...

随机推荐

  1. vue 路由动态传参 (多个)

    动态传参 传值页面  客户列表clientList.vue 路由 router.js 配置路由 接收参数的页面  客户详情CustomerDetails.vue 通过this.$router.para ...

  2. linux shell的单行多行注释

    1.单行注释,使用符号# echo " echo "test" #echo "comment“ 2. 多行注释 (1)使用 :<<!  ! file ...

  3. 【Flutter学习】页面跳转之SliverAppBar,CustomScrollView,NestedScrollView的使用

    一,flutter SliverAppbar 控件介绍 SliverAppBar “应用栏” 相当于升级版的 appbar 于 AppBar 位置的固定的应用最上面的; 而 SliverAppBar ...

  4. Comet OJ 三元组 推导+两个指针+分类讨论

    题目:https://www.cometoj.com/contest/59/problem/F?problem_id=2681 题意:给你n个三元组 ai,bi,ci,如果某一对三元组满足    2* ...

  5. error C4996: 'stricmp': The POSIX name for this item is deprecated

    转自VC错误:http://www.vcerror.com/?p=164 问题描述: 最近使用了VS2012,在使用 stricmp和ltoa函数的时候,报出了以下错误信息 error C4996: ...

  6. shell 删除除匹配字符串之外的所有文件夹

    file_dir=` -maxdepth - type d`for dir in $file_dirdo file_name=`basename $dir` if [ $file_name != &q ...

  7. 2.5 Nginx服务器基础配置实例

    pay平台nginx配置文件详解 ###全局块###   user www www; #指定运行worker process 的用户和用户组 worker_processes 4; #指定Nginx开 ...

  8. 快速调通支付宝当面付Demo

    1.访问如下地址: https://auth.alipay.com/login/ant_sso_index.htm?goto=https%3A%2F%2Fopenhome.alipay.com%2Fp ...

  9. HBase优化——读写优化

    Hbase2.0查询优化 1)设置scan缓存 HBase中Scan查询可以设置缓存,方法是setCaching(),这样可以有效的减少服务端与客户端的交互,更有效的提升扫描查询的性能. Scan s ...

  10. tonight i need your body

    wdnmd wdnmd 再lable中我们有几个不同的type参数: text     写的是文本类型的参数 password    不管输入的是什么显示的都是星星 date    输入的是一个日历本 ...