当前位置:   article > 正文

SpringBoot 集成WebSocket_springboot集成websocket

springboot集成websocket

目录

1. websocket解决的问题(服务器主动推送消息)

1.http存在的问题

2.long poll(长轮询)

3.Ajax轮询

4.websocket的改进

2.SpringBoot整合WebSocket

1、WebSocketConfig

2、WebSocketServer这里就是重点了,核心都在这里。

3.前端页面



1. websocket解决的问题(服务器主动推送消息)

1.http存在的问题

  • http是一种无状态协议,每当一次会话完成后,服务端都不知道下一次的客户端是谁,需要每次知道对方是谁,才进行相应的响应,因此本身对于实时通讯就是一种极大的障碍
  • http协议采用一次请求,一次响应,每次请求和响应就携带有大量的header头,对于实时通讯来说,解析请求头也是需要一定的时间,因此,效率也更低下
  • 最重要的是,需要客户端主动发,服务端被动发,也就是一次请求,一次响应,不能实现主动发送

2.long poll(长轮询)

  • 对于以上情况就出现了http解决的第一个方法——长轮询
  • 基于http的特性,简单点说,就是客户端发起长轮询,如果服务端的数据没有发生变更,会 hold 住请求,直到服务端的数据发生变化,或者等待一定时间超时才会返回。返回后,客户端又会立即再次发起下一次长轮询
  • 优点是解决了http不能实时更新的弊端,因为这个时间很短,发起请求即处理请求返回响应,实现了“伪·长连接”
  • 张三取快递的例子,张三今天一定要取到快递,他就一直站在快递点,等待快递一到,立马取走
  • 总的来看:
  • 推送延迟。服务端数据发生变更后,长轮询结束,立刻返回响应给客户端。

  • 服务端压力。长轮询的间隔期一般很长,例如 30s、60s,并且服务端 hold 住连接不会消耗太多服务端资源。

3.Ajax轮询

  • 基于http的特性,简单点说,就是规定每隔一段时间就由客户端发起一次请求,查询有没有新消息,如果有,就返回,如果没有等待相同的时间间隔再次询问
  • 优点是解决了http不能实时更新的弊端,因为这个时间很短,发起请求即处理请求返回响应,把这个过程放大n倍,本质上还是request = response
  • 举个形象的例子(假设张三今天有个快递快到了,但是张三忍耐不住,就每隔十分钟给快递员或者快递站打电话,询问快递到了没,每次快递员就说还没到,等到下午张三的快递到了,but,快递员不知道哪个电话是张三的,(可不是只有张三打电话,还有李四,王五),所以只能等张三打电话,才能通知他,你的快递到了)
  • 总的来看,Ajax轮询存在的问题:
  • 推送延迟。

  • 服务端压力。配置一般不会发生变化,频繁的轮询会给服务端造成很大的压力。

  • 推送延迟和服务端压力无法中和。降低轮询的间隔,延迟降低,压力增加;增加轮询的间隔,压力降低,延迟增高

4.websocket的改进

        一旦WebSocket连接建立后,后续数据都以帧序列的形式传输。在客户端断开WebSocket连接或Server端中断连接前,不需要客户端和服务端重新发起连接请求。在海量并发及客户端与服务器交互负载流量大的情况下,极大的节省了网络带宽资源的消耗,有明显的性能优势,且客户端发送和接受消息是在同一个持久连接上发起,实现了“真·长链接”,实时性优势明显。

WebSocket有以下特点:

  • 是真正的全双工方式,建立连接后客户端与服务器端是完全平等的,可以互相主动请求。而HTTP长连接基于HTTP,是传统的客户端对服务器发起请求的模式。
  • HTTP长连接中,每次数据交换除了真正的数据部分外,服务器和客户端还要大量交换HTTP header,信息交换效率很低。Websocket协议通过第一个request建立了TCP连接之后,之后交换的数据都不需要发送 HTTP header就能交换数据,这显然和原有的HTTP协议有区别所以它需要对服务器和客户端都进行升级才能实现(主流浏览器都已支持HTML5)

2.SpringBoot整合WebSocket

创建 SpringBoot项目,引入 WebSocket依赖,前端这里比较简陋。

        <!-- websocket dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.7.12</version>
        </dependency>
 

1、WebSocketConfig

启用 WebSocket的支持也是很简单。

/**
 * WebSocket配置类。开启WebSocket的支持
 */
@Configuration
public class WebSocketConfig {

    /**
     * bean注册:会自动扫描带有@ServerEndpoint注解声明的Websocket Endpoint(端点),注册成为Websocket bean。
     * 要注意,如果项目使用外置的servlet容器,而不是直接使用springboot内置容器的话,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
 

2、WebSocketServer
这里就是重点了,核心都在这里。

因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接@ServerEndpoint("/imserver/{userId}") 、@Component启用即可,然后在里面实现@OnOpen开启连接,@onClose关闭连接,@onMessage接收消息等方法。
新建一个ConcurrentHashMap用于接收当前userId的WebSocket或者Session信息,方便IM之间对userId进行推送消息。单机版实现到这里就可以。
集群版(多个ws节点)还需要借助 MySQL或者 Redis等进行订阅广播方式处理,改造对应的 sendMessage方法即可。

  1. /**
  2. * WebSocket的操作类
  3. */
  4. @Component
  5. @Slf4j
  6. /**
  7. * html页面与之关联的接口
  8. * var reqUrl = "http://localhost:8081/websocket/" + cid;
  9. * socket = new WebSocket(reqUrl.replace("http", "ws"));
  10. */
  11. @ServerEndpoint("/websocket/{sid}")
  12. public class WebSocketServer {
  13. /**
  14. * 静态变量,用来记录当前在线连接数,线程安全的类。
  15. */
  16. private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0);
  17. /**
  18. * 存放所有在线的客户端
  19. */
  20. private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();
  21. /**
  22. * 连接sid和连接会话
  23. */
  24. private String sid;
  25. private Session session;
  26. /**
  27. * 连接建立成功调用的方法。由前端<code>new WebSocket</code>触发
  28. *
  29. * @param sid 每次页面建立连接时传入到服务端的id,比如用户id等。可以自定义。
  30. * @param session 与某个客户端的连接会话,需要通过它来给客户端发送消息
  31. */
  32. @OnOpen
  33. public void onOpen(@PathParam("sid") String sid, Session session) {
  34. /**
  35. * session.getId():当前session会话会自动生成一个id,从0开始累加的。
  36. */
  37. log.info("连接建立中 ==> session_id = {}, sid = {}", session.getId(), sid);
  38. //加入 Map中。将页面的sid和session绑定或者session.getId()与session
  39. //onlineSessionIdClientMap.put(session.getId(), session);
  40. onlineSessionClientMap.put(sid, session);
  41. //在线数加1
  42. onlineSessionClientCount.incrementAndGet();
  43. this.sid = sid;
  44. this.session = session;
  45. sendToOne(sid, "连接成功");
  46. log.info("连接建立成功,当前在线数为:{} ==> 开始监听新连接:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
  47. }
  48. /**
  49. * 连接关闭调用的方法。由前端<code>socket.close()</code>触发
  50. *
  51. * @param sid
  52. * @param session
  53. */
  54. @OnClose
  55. public void onClose(@PathParam("sid") String sid, Session session) {
  56. //onlineSessionIdClientMap.remove(session.getId());
  57. // 从 Map中移除
  58. onlineSessionClientMap.remove(sid);
  59. //在线数减1
  60. onlineSessionClientCount.decrementAndGet();
  61. log.info("连接关闭成功,当前在线数为:{} ==> 关闭该连接信息:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
  62. }
  63. /**
  64. * 收到客户端消息后调用的方法。由前端<code>socket.send</code>触发
  65. * * 当服务端执行toSession.getAsyncRemote().sendText(xxx)后,前端的socket.onmessage得到监听。
  66. *
  67. * @param message
  68. * @param session
  69. */
  70. @OnMessage
  71. public void onMessage(String message, Session session) {
  72. /**
  73. * html界面传递来得数据格式,可以自定义.
  74. * {"sid":"user-1","message":"hello websocket"}
  75. */
  76. JSONObject jsonObject = JSON.parseObject(message);
  77. String toSid = jsonObject.getString("sid");
  78. String msg = jsonObject.getString("message");
  79. log.info("服务端收到客户端消息 ==> fromSid = {}, toSid = {}, message = {}", sid, toSid, message);
  80. /**
  81. * 模拟约定:如果未指定sid信息,则群发,否则就单独发送
  82. */
  83. if (toSid == null || toSid == "" || "".equalsIgnoreCase(toSid)) {
  84. sendToAll(msg);
  85. } else {
  86. sendToOne(toSid, msg);
  87. }
  88. }
  89. /**
  90. * 发生错误调用的方法
  91. *
  92. * @param session
  93. * @param error
  94. */
  95. @OnError
  96. public void onError(Session session, Throwable error) {
  97. log.error("WebSocket发生错误,错误信息为:" + error.getMessage());
  98. error.printStackTrace();
  99. }
  100. /**
  101. * 群发消息
  102. *
  103. * @param message 消息
  104. */
  105. private void sendToAll(String message) {
  106. // 遍历在线map集合
  107. onlineSessionClientMap.forEach((onlineSid, toSession) -> {
  108. // 排除掉自己
  109. if (!sid.equalsIgnoreCase(onlineSid)) {
  110. log.info("服务端给客户端群发消息 ==> sid = {}, toSid = {}, message = {}", sid, onlineSid, message);
  111. toSession.getAsyncRemote().sendText(message);
  112. }
  113. });
  114. }
  115. /**
  116. * 指定发送消息
  117. *
  118. * @param toSid
  119. * @param message
  120. */
  121. private void sendToOne(String toSid, String message) {
  122. // 通过sid查询map中是否存在
  123. Session toSession = onlineSessionClientMap.get(toSid);
  124. if (toSession == null) {
  125. log.error("服务端给客户端发送消息 ==> toSid = {} 不存在, message = {}", toSid, message);
  126. return;
  127. }
  128. // 异步发送
  129. log.info("服务端给客户端发送消息 ==> toSid = {}, message = {}", toSid, message);
  130. toSession.getAsyncRemote().sendText(message);
  131. /*
  132. // 同步发送
  133. try {
  134. toSession.getBasicRemote().sendText(message);
  135. } catch (IOException e) {
  136. log.error("发送消息失败,WebSocket IO异常");
  137. e.printStackTrace();
  138. }*/
  139. }
  140. }

3.前端页面

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>666666</title>
  6. </head>
  7. <body>
  8. 传递来的数据值cid:
  9. <input type="text" th:value="${cid}" id="cid"/>
  10. <p>【toUserId】:
  11. <div><input id="toUserId" name="toUserId" type="text" value="user-1"></div>
  12. <p>【toUserId】:
  13. <div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
  14. <p>【操作】:
  15. <div>
  16. <button type="button" onclick="sendMessage()">发送消息</button>
  17. </div>
  18. </body>
  19. <script type="text/javascript">
  20. var socket;
  21. if (typeof (WebSocket) == "undefined") {
  22. console.log("您的浏览器不支持WebSocket");
  23. } else {
  24. console.log("您的浏览器支持WebSocket");
  25. //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  26. var cid = document.getElementById("cid").value;
  27. console.log("cid-->" + cid);
  28. var reqUrl = "http://localhost:8081/websocket/" + cid;
  29. socket = new WebSocket(reqUrl.replace("http", "ws"));
  30. //打开事件
  31. socket.onopen = function () {
  32. console.log("Socket 已打开");
  33. //socket.send("这是来自客户端的消息" + location.href + new Date());
  34. };
  35. //获得消息事件
  36. socket.onmessage = function (msg) {
  37. console.log("onmessage--" + msg.data);
  38. //发现消息进入 开始处理前端触发逻辑
  39. };
  40. //关闭事件
  41. socket.onclose = function () {
  42. console.log("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. function sendMessage() {
  56. if (typeof (WebSocket) == "undefined") {
  57. console.log("您的浏览器不支持WebSocket");
  58. } else {
  59. // console.log("您的浏览器支持WebSocket");
  60. var toUserId = document.getElementById('toUserId').value;
  61. var contentText = document.getElementById('contentText').value;
  62. var msg = '{"sid":"' + toUserId + '","message":"' + contentText + '"}';
  63. console.log(msg);
  64. socket.send(msg);
  65. }
  66. }
  67. </script>
  68. </html>

参考: 

 1.websocket和http区别_cwxcc的博客-CSDN博客

2. SpringBoot 集成WebSocket详解_springboot集成websocket_Charge8的博客-CSDN博客

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

闽ICP备14008679号