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

最新文章

  1. 51Nod 1268 和为K的组合
  2. Vue.js 整理笔记
  3. 使用TFS 自动编译时的一点设置
  4. CTO和技术副总裁应该如何分工?谁才是技术领导者?
  5. JavaScript:JSON
  6. 如何用参数化SQL语句污染你的计划缓存
  7. Android5.0新特性——阴影和剪裁(shadow)
  8. JavaScript 技巧总结
  9. lz4,pigz,gzip 3者比较
  10. HDUOJ--------A simple stone game(尼姆博弈扩展)(2008北京现场赛A题)
  11. 利用CMake自己创建OpenCV静态链接库
  12. 开心菜鸟系列学习笔记--------初探Nodejs(了解篇)
  13. python mysql多条插入
  14. Windows 使用 Visual Studio 编译 caffe
  15. Loj #3093. 「BJOI2019」光线
  16. Python001-操作MSSQL(Microsoft sql server)基础示例(一)
  17. poj 3903 poj 2533 (LIS模板题)
  18. Django使用admin管理后台管理数据库表
  19. 《图说VR入门》——入门汇总
  20. [GO]小技巧,如何实现一个链式操作

热门文章

  1. SpringBoot2.0总结
  2. Spark开发环境搭建和作业提交
  3. [NOIP模拟25]题解
  4. IDEA的骚操作
  5. PHP如何进行错误与异常处理(PHP7中的异常处理和之前版本异常处理的区别)
  6. MySQL 时间戳与日期格式的相互转换(转)
  7. Codeforces Round #499 (Div. 2) Problem-A-Stages(水题纠错)
  8. Eureka 系列(06)消息广播(下):TaskDispacher 之 Acceptor - Worker 模式
  9. [轉]sendpage漏洞分析 CVE-2009-2692
  10. Python第九节 条件和循环