当前位置:   article > 正文

webSocket介绍与使用 spring boot 集成 websocket教程 java_springboot websocket

springboot websocket

目录

一、WebSocket简介

二、WebSocket优缺点

三、spring boot集成webSocket

四、验证


一、WebSocket简介

        WebSocket建立在TCP协议上,是一种在单个TCP连接上进行全双工通信的协议。

        HTML5里面提出了WebSocket标准,目的是让服务器具有“主送”向浏览器推送信息的能力,它允许客户端和服务器之间建立持久连接,实现实时的数据传输功能。

WebSocket通讯分为两个阶段:

1.握手阶段

        客户端通过HTTP请求发起握手请求,请求头包含一些特殊字段,如pgrade:websocket和Connection:Upgrade以及其他的WebSocket相关字段。

服务器收到客户端的WebSocket握手请求后,进行协议升级,将HTTP升级为WebSocket连接。服务器返回一个WebSocket握手响应,相应头中包如:Upgrade:websocket和Connection:Upgrade等WebSocket相关字段。

客户端收到服务器的WebSocket握手响应后,WebSocket连接就建立成功,客户端和服务端都可以发送和接收WebSocket消息。

2.数据交换阶段

        WebSocket建立成功后,客户端和服务器都可以通过WebSocket会话进行实时的双向数据交换。同时,客户端和服务端可以通过发送心跳数据帧来维持连接,如果在一段时间内没有收到心跳响应,则断开WebSocket连接。

二、WebSocket优缺点

1.优点

        支持双向通讯,实时性比较高,更加灵活。

        开销少,ws建立成功后,客户端、服务端进行数据交换,协议控制的数据包头部较小。http需要完整的头部信息。

        可扩展,WebSocket协议定义了扩展,用户可以扩展协议。

2.缺点

        服务端需要支持WebSocket协议。

        客户端连接数多,服务端压力大。

三、spring boot集成webSocket

1.新建spring boot项目,再pom.xml加入以下配置

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.18.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <!-- webSocket依赖包 -->
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-websocket</artifactId>
  16. </dependency>
  17. </dependencies>

2.再spring boot启动类开启websocket功能

  1. package com.example.demo;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  5. //开启WebSocket
  6. @EnableWebSocket
  7. @SpringBootApplication
  8. public class DemoApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(DemoApplication.class, args);
  11. }
  12. }

3.新建WebSoketConfig配置类

  1. package com.example.demo.common.config.websocket;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. /**
  6. * WebSocket配置类
  7. */
  8. @Configuration
  9. public class WebSocketConfig {
  10. @Bean
  11. public ServerEndpointExporter serverEndpointExporter() {
  12. return new ServerEndpointExporter();
  13. }
  14. }

4.新建WebSocketServer服务类

  1. package com.example.demo.common.config.websocket;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.*;
  4. import javax.websocket.server.PathParam;
  5. import javax.websocket.server.ServerEndpoint;
  6. import java.io.IOException;
  7. import java.util.concurrent.ConcurrentHashMap;
  8. /**
  9. * @ServerEndpoint:该注解用于暴漏外部ws的路径,类似@RequestMapping注解。例如服务端口8080,请求地址:ws://localhost:8080/myWs
  10. * 路径上{userId} 可在onOpen连接成功方法使用@PathParam("userId") String userId接收数据
  11. */
  12. @ServerEndpoint("/myWs/{userId}")
  13. @Component
  14. public class WebSocketServer {
  15. //线程安全的map,用来保存每个客户端对应的WebSocket对象
  16. private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
  17. //单个客户端的session,通过session与对应客户端通讯
  18. private Session session;
  19. //用户id
  20. private String userId;
  21. /**
  22. * 连接成功
  23. * @OnOpen注解:websocket 连接成功后,触发该注解修饰的方法
  24. * @param session
  25. */
  26. @OnOpen
  27. public void onOpen(Session session, @PathParam("userId") String userId) {
  28. this.session = session;
  29. this.userId = userId;
  30. if (webSocketMap.containsKey(userId)) {
  31. webSocketMap.remove(userId);
  32. webSocketMap.put(userId, this);
  33. } else {
  34. webSocketMap.put(userId, this);
  35. }
  36. System.out.println("连接成功");
  37. }
  38. /**
  39. * 连接关闭
  40. * @OnClose注解:websocket断开连接后,触发该注解修饰的方法
  41. * @param session
  42. */
  43. @OnClose
  44. public void onCLose(Session session) {
  45. if (webSocketMap.containsKey(userId)) {
  46. webSocketMap.remove(userId);
  47. }
  48. System.out.println("关闭连接");
  49. }
  50. /**
  51. * 接收消息
  52. * @OnMessage注解:客户端发送消息时,触发该注解声明的方法
  53. * @param text
  54. * @return
  55. */
  56. @OnMessage
  57. public void onMessage(String text) {
  58. System.out.println("后端接收前端web发送数据userId:" + userId + ",接收信息:" + text);
  59. if (webSocketMap.containsKey(userId)) {
  60. try {
  61. webSocketMap.get(userId).session.getBasicRemote().sendText("返回web数据userId:" + userId + ",返回消息:" + text);
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. }
  67. /**
  68. * 连接异常
  69. * @OnError注解:当建立的连接出现异常后,触发该注解修饰的方法
  70. * @param session
  71. * @param throwable
  72. */
  73. @OnError
  74. public void onError(Session session, Throwable throwable) {
  75. System.out.println("websocket连接异常:" + throwable.getMessage());
  76. }
  77. /**
  78. * 服务器给指定WebSocket客户端发送信息
  79. * @param userId
  80. * @param message
  81. */
  82. public static void sendInfo(String userId, String message) {
  83. System.out.println("后端发送前端web数据userId:" + userId + "发送消息:" + message);
  84. if (webSocketMap.containsKey(userId)) {
  85. try {
  86. webSocketMap.get(userId).session.getBasicRemote().sendText("后端发送前端web数据userId" + userId + ",内容:" + message);
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. }
  92. }

5.新建DemoController测试类,增加接口通过webSocket给客户端发信信息

  1. package com.example.demo.controller;
  2. import com.example.demo.common.config.websocket.WebSocketServer;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class DemoController {
  8. @RequestMapping("/demo")
  9. public boolean demo(@RequestParam("userId") String userId, @RequestParam("message") String mesage) {
  10. //给前端web推送数据
  11. WebSocketServer.sendInfo(userId, mesage);
  12. return true;
  13. }
  14. }

四、验证

1.启动服务,访问websocket在线测试页面,与后端建立连接

2.后端显示连接成功

3.通过websocket给后端发送数据

4.后端打印接收到的数据

5.调用后端接口,通过websocket给前端推送数据

6.websocket在线测试页面收到数据

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

闽ICP备14008679号