SpringBoot2 集成 WebSocket

Stella981
• 阅读 523
  1.  <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-websocket</artifactId>
     </dependency>
    
  2.   1 package me.abdusalam.websocket.demo.config;
      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 @Configuration
      8 public class WebSocketConfig {
      9 
     10     @Bean
     11     public ServerEndpointExporter serverEndpointExporter() {
     12         return new ServerEndpointExporter();
     13     }
     14 
     15 }
    
  3.   1 package me.abdusalam.websocket.demo.dao;
      2 import me.abdusalam.websocket.demo.server.WebSocketServer;
      3 import java.util.concurrent.CopyOnWriteArraySet;
      4 
      5 // 模拟数据库
      6 public class DB {
      7 
      8     /**
      9      * 记录 有多少个客户端【前端浏览器】与服务端【后端】创建连接 的个数
     10      * 应该把它设计成线程安全的 , 使用 synchronized 进行操作
     11      */
     12     private static Integer connectedClientNum = 0;
     13     public static synchronized void increaseConnectedClientNum() {
     14         connectedClientNum++;
     15     }
     16     public static synchronized void decreaseConnectedClientNum() {
     17         connectedClientNum--;
     18     }
     19     
     20     /**
     21      * java.util.concurrent 包的线程安全的 Set 集合
     22      * 客户端【前端浏览器】 每次 使用 new WebSocket("ws://localhost:8080/websocket") 时,即与服务端【后端】创建连接时,后端 new 一个 WebSocketServer
     23      *      【 可见 WebSocketServer 是多例的 --> 前端有多少个 new WebSocket("ws://localhost:8080/websocket")   就后端有多少个 new WebSocketServer 】
     24      * WebSocketServers 用来存储 总共有多少个 WebSocketServer 被 new 了
     25      */
     26     public static CopyOnWriteArraySet<WebSocketServer> webSocketServers = new CopyOnWriteArraySet<>();
     27 
     28 }
    
  4.   1 package me.abdusalam.websocket.demo.server;
      2 import java.io.IOException;
      3 import javax.websocket.OnClose;
      4 import javax.websocket.OnError;
      5 import javax.websocket.OnMessage;
      6 import javax.websocket.OnOpen;
      7 import javax.websocket.Session;
      8 import javax.websocket.server.ServerEndpoint;
      9 import me.abdusalam.websocket.demo.dao.DB;
     10 import org.springframework.stereotype.Component;
     11 
     12 @Component
     13 @ServerEndpoint("/WebSocketServer")
     14 public class WebSocketServer {
     15 
     16     /**
     17      * 与某一个客户端的连接会话
     18      * 用这个 session 向客户端发消息
     19      */
     20     private Session session;
     21 
     22     // 向所有客户端【浏览器】发消息
     23     public static void sendMessage2allClients(String message){
     24         for (WebSocketServer item : DB.webSocketServers) {
     25             try {
     26                 // 发消息
     27                 item.session.getBasicRemote().sendText(message);
     28             } catch (IOException e) {
     29                 // 给某一个客户端【浏览器】发消息抛异常,没关系,继续给下一个客户端【浏览器】发消息
     30                 continue;
     31             }
     32         }
     33     }
     34 
     35 
     36     // 当前端创建连接【 new WebSocket("ws://localhost:8080/websocket") 】时,调用的方法
     37     @OnOpen
     38     public void clientConnected(Session session) {
     39         DB.increaseConnectedClientNum();
     40         DB.webSocketServers.add(this);
     41         this.session = session;
     42         sendMessage2allClients("系统消息:SESSION_ID 为 " + this.session.getId() + " 的客户端连接成功");
     43     }
     44 
     45 
     46     // 收到客户端【浏览器】消息后调用的方法
     47     @OnMessage
     48     public void receiveMessageFromClient(String message) {
     49         sendMessage2allClients("SESSION_ID " + this.session.getId() + " : " + message);
     50     }
     51 
     52 
     53     //
     54     @OnError
     55     public void onError(Throwable error) {
     56         error.printStackTrace();
     57     }
     58 
     59 
     60     // 连接关闭调用的方法
     61     @OnClose
     62     public void onClose() {
     63         DB.decreaseConnectedClientNum();
     64         DB.webSocketServers.remove(this);
     65         sendMessage2allClients("系统消息:SESSION_ID 为 " + this.session.getId() + " 的客户端断开了连接");
     66     }
     67 
     68 }
    
  5.   1 package me.abdusalam.websocket.demo.controller;
      2 import me.abdusalam.websocket.demo.server.WebSocketServer;
      3 import org.springframework.web.bind.annotation.*;
      4 
      5 @RestController
      6 @RequestMapping("/controller")
      7 public class Controller {
      8 
      9     //推送数据接口
     10     @PostMapping("/sendMessage2allClients")
     11     public void sendMessage2allClients(String message) {
     12         WebSocketServer.sendMessage2allClients( message );
     13     }
     14 }
    
  6.   1 <!DOCTYPE html>
      2 <html lang="en">
      3 <head>
      4     <meta charset="UTF-8">
      5     <title>WebSocket Demo</title>
      6     <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
      7 </head>
      8 <body>
      9 
     10     <h1 style="text-align: center" id="h1"></h1>
     11     <h3 style="padding: 10px">消息展示区:</h3>
     12     <div style="border: 5px solid blue;padding: 10px;" id="div"></div>
     13 
     14     <button onclick="send()">发送</button>
     15 
     16     <script>
     17         if(typeof(WebSocket) == "undefined") {
     18             alert("您的浏览器不支持WebSocket");
     19         }else{
     20 
     21             // 实例化 WebSocket 对象,指定要连接的服务器地址与端口  建立连接
     22             var ws = new WebSocket("ws://localhost:8080/WebSocketServer");
     23 
     24             // 用来消息展示的 div
     25             var div = document.getElementById("div");
     26 
     27             // 打开事件
     28             ws.onopen = function() {
     29                 document.getElementById("h1").innerText = "您已经成功连上服务端了";
     30 
     31                 // 可以使用 ws.send("消息内容") 向服务端发消息
     32             };
     33 
     34             // 获得消息事件
     35             ws.onmessage = function(msg) {
     36                 div.innerHTML = div.innerHTML + "<div style='margin: 10px;'>" + msg.data + "</div>";
     37             };
     38 
     39             // 关闭事件
     40             // ws.onclose = function() {
     41             //    console.log("已关闭");
     42             // };
     43 
     44             // 发生了错误事件
     45             ws.onerror = function() {
     46                 alert("发生了错误");
     47                 //此时可以尝试刷新页面
     48             }
     49 
     50             function send() {
     51                 $.post( '/controller/sendMessage2allClients', {message:prompt("请输入:")}, function(response){} );
     52             }
     53         }
     54     </script>
     55 </body>
     56 </html>
    

    SpringBoot2 集成 WebSocket


    SpringBoot2 集成 WebSocket


    SpringBoot2 集成 WebSocket


    SpringBoot2 集成 WebSocket


    SpringBoot2 集成 WebSocket

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
ES6 新增的数组的方法
给定一个数组letlist\//wu:武力zhi:智力{id:1,name:'张飞',wu:97,zhi:10},{id:2,name:'诸葛亮',wu:55,zhi:99},{id:3,name:'赵云',wu:97,zhi:66},{id:4,na
Easter79 Easter79
2年前
SpringBoot2 集成 WebSocket
1.<dependency<groupIdorg.springframework.boot</groupId<artifactIdspringbootstarterwebsocket</artifactId</dependency2.
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这