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. pipeline语法之environment,dir(),deleteDir()方法,readJSON,writeJSON

    一 environment指令指定一系列键值对,这些对值将被定义为所有步骤的环境变量或阶段特定步骤 environment{…}, 大括号里面写一些键值对,也就是定义一些变量并赋值,这些变量就是环境变 ...

  2. JSON和fastjson

    一.JSON 语法规则: 数据在名称/值对中 数据由逗号分隔 花括号保存对象 方括号保存数组 名称/值对-->对象-->数组 JSON 名称/值对 JSON 数据的书写格式是:名称/值对. ...

  3. 【leetcode】990. Satisfiability of Equality Equations

    题目如下: Given an array equations of strings that represent relationships between variables, each strin ...

  4. FastDFSClient上传图片工具类

    package cn.lijun.core.util; import org.apache.commons.io.FilenameUtils;import org.csource.common.Nam ...

  5. PHP curl_multi_select函数

    curl_multi_select — 等待所有cURL批处理中的活动连接 说明 int curl_multi_select ( resource $mh [, float $timeout = 1. ...

  6. POJ 3414 Pots (dfs,这个代码好长啊QAQ)

    Description You are given two pots, having the volume of A and B liters respectively. The following ...

  7. 【dart学习】之字典(Map)的相关方法总结

    一,概述 通常来讲,Map是一个键值对相关的对象,键和值可以是任何类型的对象.每个键只出现一次,而一个值则可以出现多次.映射是动态集合. 换句话说,Maps可以在运行时增长和缩小. dart:core ...

  8. 【Flutter学习】页面跳转之路由及导航

    一,概述 移动应用通常通过成为‘屏幕’或者‘页面’的全屏元素显示其内容,在Flutter中,这些元素统称为路由,它们由导航器Navigator组件管理.导航器管理一组路由Route对象,并提供了管理堆 ...

  9. SqlServer2008跨服务器操作

    --创建链接服务器 exec sp_addlinkedserver @server= 'SQL2' --链接服务器名 , @srvproduct= '' --OLE DB 数据源的产品名称:如果为 S ...

  10. linux基础知识汇总(二)-vi/vim

    转:http://blog.csdn.net/sky04/article/details/5662582 vi与vim一样都是编辑器,不同的是vim更高级一些,可以理解是vi的高级版本.vi就像Win ...