当前位置:   article > 正文

若依框架集成WebSocket_若依websocket

若依websocket

一、WebSocket

1、WebSocket是什么

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

        WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

 

2、为什么要使用WebSocket?

        WebSocket只需要完成一次握手就能完成数据的双向传递,这种方式极为方便我们去做定时的查询,例如我们在前端收到用户支付过后,后台页面需要做出相应的语音提醒和信息弹窗去提示我们后台管理人员

二、若依框架集成WebSocket的使用

1、引入pom依赖

  1. <!--websocket-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-websocket</artifactId>
  5. </dependency>

2、定义一个WebSocketConfig类到framwork模块

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. /**
  5. * 开启WebSocket支持
  6. */
  7. @Configuration
  8. public class WebSocketConfig {
  9. @Bean
  10. public ServerEndpointExporter serverEndpointExporter() {
  11. return new ServerEndpointExporter();
  12. }
  13. }

3、定义一个WebSocketServer类

这个类主要用于使用创建连接、监听消息和发送消息等

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

4、前端页面的配置

  1. <div id="wrap" v-show="false">
  2. <audio v-if="false" src="@/api/audio/preview.mp3" id="audio" preload="auto" muted autoplay type="audio/mp3" controls="controls" >
  3. <span id="audioId">播放音乐</span>
  4. </audio>
  5. </div>
  6. created() {
  7. this.initWebSocket();
  8. },
  9. destroyed() {
  10. this.websock.close() //离开路由之后断开websocket连接
  11. },
  12. methods: {
  13. initWebSocket(){
  14. const wsuri = "ws://localhost:8080/ws/123214";
  15. if(typeof(WebSocket) == "undefined") {
  16. console.log("您的浏览器不支持WebSocket");
  17. }else{
  18. console.log(wsuri)
  19. this.websock = new WebSocket(wsuri);
  20. this.websock.onmessage = this.websocketonmessage;
  21. this.websock.onopen = this.websocketonopen;
  22. this.websock.onerror = this.websocketonerror;
  23. this.websock.onclose = this.websocketclose;
  24. }
  25. },
  26. //连接建立之后执行send方法发送数据
  27. websocketonopen(){
  28. let actions = {"test":"我已在线"};
  29. this.websocketsend(JSON.stringify(actions));
  30. },
  31. //连接建立失败重连
  32. websocketonerror(){
  33. this.initWebSocket();
  34. },
  35. //数据接收
  36. websocketonmessage(e){
  37. this.$modal.msg(e.data);
  38. console.log(e.data);
  39. var audio = document.querySelector("audio");//用这种标签名称获取的方式就不会报错了,,,,
  40. audio.currentTime = 0;//从头开始播放
  41. audio.muted = false;//取消静音
  42. audio.play();//音频播放
  43. // const redata = JSON.parse(e.data);
  44. },
  45. //数据发送
  46. websocketsend(Data){
  47. this.websock.send(Data);
  48. },
  49. //关闭
  50. websocketclose(e){
  51. console.log('断开连接',e);
  52. },
  53. }

audio是因为业务场景需要引入的,主要是对与来订单提醒的提示音,然后可以在websocketonmessage()接受数据和进行处理

5、SecurityConfig设置匿名访问

这个主要是方便我们测试

image.png

 整体结构(仅供参考)

image.png

 6、测试

        大家可以使用若依的定时任务,去写一下业务逻辑,然后在后台管理的定时任务里面可以去执行一次定时任务,去观察页面和后台日志的变化,给前台发送数据就是调用WebSocketServer类里面的sendInfo()方法,参数第一个是你要发送的消息,第二个是sid就是你建立连接的那个sid

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

闽ICP备14008679号