当前位置:   article > 正文

Spring Boot 使用WebSocket、SockJS、STOMP实现消息功能(二)

Spring Boot 使用WebSocket、SockJS、STOMP实现消息功能(二)

一、介绍

在我学习websocket期间,有两种实现手段。第一种是用原生的代码来实现websocket消息推送,第二种就是基于SocketJS+Stomp来实现的。这里主要讲一下第一种的实现:

(一)WebSocket简介
  WebSocket是一种通讯协议,通过单个TCP连接提供完全多工通讯管道。大白话就是:WebSocket协议相对于Http协议来说,它能在一段时间内一直保持连接,而Http协议是三次握手后就断开连接。WebSocket经常用于聊天室这种实时通讯场景。

  WebSocket协议地址相对于Http协议地址来说,Schema部分变了:Http地址:http://host:port/… ,而WebSocke地址:ws://host:port/…

(二)WebSocke API
  相关术语:

  • 端点(Endpoint)
  • 连接(Connection)
  • 对点(Peer)
  • 会话(Session)
  • 客户端端点、服务器端点

(三)端点生命周期

  • 打开连接

  Endpoint#onOpen(Session,EndpointConfig) ------编程
  @OnOpen ------注解

  • 关闭连接

  Endpoint#onClose(Session,CloseReason)
  @OnClose

  • 错误

  Endpoint#onError(Session,Throwable)
  @OnError

  • 发送消息

  @OnMessage(PS:无对应编程方法)

(四)会话(Sessions)

  • API:javax.websocket.Session
  • 接收消息:javax.websocket.MessageHandler
  • 发送消息:javax.websocket.RemoteEndpoint.Basic

(五)配置(Configuration)

  • 服务端配置(javax.websocket.ServerEndpointConfig)
  1. URI 映射
  2. 子协议协商
  3. 扩展点修改
  4. Origin检测
  5. 握手修改
  6. 自定义端点创建
  • 客户端配置(javax.websocket.ClientEndpointConfig)
  1. 子协议
  2. 扩展点
  3. 客户端配置修改

该demo主要用来学习用可以体验这种方式实现的简单功能,能更好的了解websocket的底层实现。

二、环境要求和关键技术

三、maven依赖

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>web</groupId>
  7. <artifactId>socket-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.0.2.RELEASE</version>
  13. <relativePath/>
  14. </parent>
  15. <dependencyManagement>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-dependencies</artifactId>
  20. <version>Finchley.RC2</version>
  21. <type>pom</type>
  22. <scope>import</scope>
  23. </dependency>
  24. </dependencies>
  25. </dependencyManagement>
  26. <properties>
  27. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  28. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  29. <java.version>1.8</java.version>
  30. <spring.cloud.version>Finchley.RC2</spring.cloud.version>
  31. <fastjson.version>1.2.47</fastjson.version>
  32. <commons-lang.version>2.6</commons-lang.version>
  33. <mybatis.version>1.3.2</mybatis.version>
  34. <mysql.version>5.1.46</mysql.version>
  35. <druid.version>1.1.10</druid.version>
  36. <lombok.version>1.16.20</lombok.version>
  37. <spring.security.version>4.1.0.RELEASE</spring.security.version>
  38. <log4j.version>1.2.16</log4j.version>
  39. </properties>
  40. <dependencies>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-web</artifactId>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.springframework.boot</groupId>
  47. <artifactId>spring-boot-starter-test</artifactId>
  48. <scope>test</scope>
  49. </dependency>
  50. <dependency>
  51. <groupId>com.alibaba</groupId>
  52. <artifactId>fastjson</artifactId>
  53. <version>${fastjson.version}</version>
  54. </dependency>
  55. <dependency>
  56. <groupId>commons-lang</groupId>
  57. <artifactId>commons-lang</artifactId>
  58. <version>${commons-lang.version}</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>mysql</groupId>
  62. <artifactId>mysql-connector-java</artifactId>
  63. <version>${mysql.version}</version>
  64. </dependency>
  65. <dependency>
  66. <groupId>com.alibaba</groupId>
  67. <artifactId>druid</artifactId>
  68. <version>${druid.version}</version>
  69. </dependency>
  70. <dependency>
  71. <groupId>org.projectlombok</groupId>
  72. <artifactId>lombok</artifactId>
  73. <version>${lombok.version}</version>
  74. <scope>provided</scope>
  75. </dependency>
  76. <dependency>
  77. <groupId>log4j</groupId>
  78. <artifactId>log4j</artifactId>
  79. <version>${log4j.version}</version>
  80. <scope>compile</scope>
  81. </dependency>
  82. <dependency>
  83. <groupId>org.springframework.boot</groupId>
  84. <artifactId>spring-boot-starter-websocket</artifactId>
  85. </dependency>
  86. <dependency>
  87. <groupId>org.springframework.boot</groupId>
  88. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  89. </dependency>
  90. </dependencies>
  91. <build>
  92. <plugins>
  93. <plugin>
  94. <groupId>org.springframework.boot</groupId>
  95. <artifactId>spring-boot-maven-plugin</artifactId>
  96. </plugin>
  97. </plugins>
  98. </build>
  99. <repositories>
  100. <repository>
  101. <id>spring-milestones</id>
  102. <name>Spring Milestones</name>
  103. <url>https://repo.spring.io/libs-milestone</url>
  104. <snapshots>
  105. <enabled>false</enabled>
  106. </snapshots>
  107. </repository>
  108. </repositories>
  109. </project>

启动类SockerApplication.java

  1. package com.wyc;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SockerApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(SockerApplication.class,args);
  8. }
  9. }

 端点配置WebSocketConfig.java

  1. package com.wyc.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
  5. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  6. @Configuration
  7. public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
  8. @Bean
  9. public ServerEndpointExporter serverEndpointExporter(){
  10. return new ServerEndpointExporter();
  11. }
  12. }

CheckCenterController.java 

  1. package com.wyc.controller;
  2. import com.wyc.util.WebSocketServer;
  3. import org.springframework.scheduling.annotation.Scheduled;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.servlet.ModelAndView;
  7. import java.io.IOException;
  8. /**
  9. * 消息推送
  10. *
  11. * @author :WYC
  12. * @create 2018-07-11 14:12
  13. **/
  14. @Controller
  15. @RequestMapping("/checkcenter")
  16. public class CheckCenterController {
  17. @RequestMapping("/fllindex")
  18. public String getIndex(){
  19. System.out.println("主页面");
  20. return "socket";
  21. }
  22. //页面请求
  23. @GetMapping("/socket/{cid}")
  24. public ModelAndView socket(@PathVariable String cid) {
  25. ModelAndView mav=new ModelAndView("/socket");
  26. mav.addObject("cid", cid);
  27. return mav;
  28. }
  29. //推送数据接口
  30. @ResponseBody
  31. @RequestMapping("/socket/push/{cid}")
  32. public String pushToWeb(@PathVariable String cid,String message) {
  33. try {
  34. WebSocketServer.sendInfo(message,cid);
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. return cid+"#"+e.getMessage();
  38. }
  39. return cid;
  40. }
  41. }

WebSocketServer.java 

  1. package com.wyc.util;
  2. import org.apache.juli.logging.Log;
  3. import org.apache.juli.logging.LogFactory;
  4. import org.springframework.stereotype.Component;
  5. import javax.websocket.*;
  6. import javax.websocket.server.PathParam;
  7. import javax.websocket.server.ServerEndpoint;
  8. import java.io.IOException;
  9. import java.util.concurrent.CopyOnWriteArraySet;
  10. /**
  11. * WebSocket服务类
  12. *
  13. * @author :WYC
  14. * @create 2018-07-11 13:54
  15. **/
  16. @ServerEndpoint("/websocket/{sid}")
  17. @Component
  18. public class WebSocketServer {
  19. static Log log=LogFactory.getLog(WebSocketServer.class);
  20. //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  21. private static int onlineCount = 0;
  22. //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
  23. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  24. //与某个客户端的连接会话,需要通过它来给客户端发送数据
  25. private Session session;
  26. //接收sid
  27. private String sid="";
  28. /**
  29. * 连接建立成功调用的方法*/
  30. @OnOpen
  31. public void onOpen(Session session,@PathParam("sid") String sid) {
  32. this.session = session;
  33. webSocketSet.add(this); //加入set中
  34. addOnlineCount(); //在线数加1
  35. log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
  36. this.sid=sid;
  37. try {
  38. sendMessage("连接成功");
  39. } catch (IOException e) {
  40. log.error("websocket IO异常");
  41. }
  42. }
  43. /**
  44. * 连接关闭调用的方法
  45. */
  46. @OnClose
  47. public void onClose() {
  48. webSocketSet.remove(this); //从set中删除
  49. subOnlineCount(); //在线数减1
  50. log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
  51. }
  52. /**
  53. * 收到客户端消息后调用的方法
  54. *
  55. * @param message 客户端发送过来的消息*/
  56. @OnMessage
  57. public void onMessage(String message, Session session) {
  58. log.info("收到来自窗口"+sid+"的信息:"+message);
  59. //群发消息
  60. for (WebSocketServer item : webSocketSet) {
  61. try {
  62. while (true){
  63. item.sendMessage(message);
  64. }
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. /**
  71. *
  72. * @param session
  73. * @param error
  74. */
  75. @OnError
  76. public void onError(Session session, Throwable error) {
  77. log.error("发生错误");
  78. error.printStackTrace();
  79. }
  80. /**
  81. * 实现服务器主动推送
  82. */
  83. public void sendMessage(String message) throws IOException {
  84. this.session.getBasicRemote().sendText(message);
  85. }
  86. /**
  87. * 群发自定义消息
  88. * */
  89. public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
  90. log.info("推送消息到窗口"+sid+",推送内容:"+message);
  91. for (WebSocketServer item : webSocketSet) {
  92. try {
  93. //这里可以设定只推送给这个sid的,为null则全部推送
  94. if(sid==null) {
  95. item.sendMessage(message);
  96. }else if(item.sid.equals(sid)){
  97. item.sendMessage(message);
  98. }
  99. } catch (IOException e) {
  100. continue;
  101. }
  102. }
  103. }
  104. public static synchronized int getOnlineCount() {
  105. return onlineCount;
  106. }
  107. public static synchronized void addOnlineCount() {
  108. WebSocketServer.onlineCount++;
  109. }
  110. public static synchronized void subOnlineCount() {
  111. WebSocketServer.onlineCount--;
  112. }
  113. }

前端页面socket.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <base href="<%=basePath%>">
  5. <meta charset="UTF-8">
  6. <meta name="viewport"
  7. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  8. <title>弹窗</title>
  9. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  10. <!-- <script type="text/javascript" src="../js/FileSaver.js"></script>-->
  11. </head>
  12. <body>
  13. <h2>33</h2>
  14. <input id="start">
  15. <input id="message">
  16. <iframe id="my_iframe" style="display:none;"></iframe>
  17. <script type="application/javascript">
  18. var socket;
  19. if(typeof(WebSocket) == "undefined") {
  20. console.log("您的浏览器不支持WebSocket");
  21. }else{
  22. console.log("您的浏览器支持WebSocket");
  23. //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  24. //等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
  25. //socket = new WebSocket("http://localhost:8080/websocket/${cid}".replace("http","ws"));
  26. socket = new WebSocket("ws://localhost:8080/websocket/33");
  27. //打开事件
  28. socket.onopen = function() {
  29. console.log("Socket 已打开");
  30. $("#start").val("Socket 已打开")
  31. //socket.send("这是来自客户端的消息" + location.href + new Date());
  32. };
  33. //获得消息事件
  34. socket.onmessage = function(msg) {
  35. console.log(msg.data);
  36. $("#message").val(msg.data)
  37. //发现消息进入 开始处理前端触发逻辑
  38. };
  39. //关闭事件
  40. socket.onclose = function() {
  41. console.log("Socket已关闭");
  42. $("#close").val("Socket已关闭")
  43. };
  44. //发生了错误事件
  45. socket.onerror = function() {
  46. alert("Socket发生了错误");
  47. //此时可以尝试刷新页面
  48. }
  49. //离开页面时,关闭socket
  50. //jquery1.8中已经被废弃,3.0中已经移除
  51. // $(window).unload(function(){
  52. // socket.close();
  53. //});
  54. }
  55. </script>
  56. </body>
  57. </html>

github源码:https://github.com/wangyuanchen/socketdemo

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/178663
推荐阅读
相关标签
  

闽ICP备14008679号