• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SpringBoot整合WebSocket实现后端向前端发送消息

武飞扬头像
Eliauk-_-
帮助1

目录

一、什么是 websocket 接口

二、适用场景

三、示例代码

3.1、添加pom.xml依赖

3.2、创建WebSokcet配置类

3.3、创建测试发送消息接口

3.4、测试webSocket(http://www.jsons.cn/websocket/)


一、什么是 websocket 接口


使用 websocket 建立长连接,服务端和客户端可以互相通信,服务端只要有数据更新,就可以主动推给客户端。

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

二、适用场景

在业务开发过程中碰到一些异步处理(微信支付、支付宝支付的支付通知),跨应用的消息传递。

当业务执行完毕后,需要将成功的信息投递给前端。一般情况下都是前端调用后端的http/https接口获取数据,后端想要主动推送消息给前端就需要使用到WebSocket进行前后端的通信。

三、示例代码

3.1、添加pom.xml依赖

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

3.2、创建WebSokcet配置类

  1.  
    @Configuration
  2.  
    public class WebSocketConfig {
  3.  
    @Bean
  4.  
    public ServerEndpointExporter serverEndpointExporter(){
  5.  
    return new ServerEndpointExporter();
  6.  
    }
  7.  
    }
  8.  
    3.3、创建WebSokcet工具类
  9.  
     
  10.  
    @ServerEndpoint(value = "/websocket")
  11.  
    @Component
  12.  
    public class WebSocketServer {
  13.  
    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
  14.  
     
  15.  
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  16.  
    private static int onlineCount = 0;
  17.  
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
  18.  
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  19.  
     
  20.  
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
  21.  
    private Session session;
  22.  
     
  23.  
    /**
  24.  
    * 连接建立成功调用的方法
  25.  
    */
  26.  
    @OnOpen
  27.  
    public void onOpen(Session session) {
  28.  
    this.session = session;
  29.  
    //加入set中
  30.  
    webSocketSet.add(this);
  31.  
    //在线数加1
  32.  
    addOnlineCount();
  33.  
    log.info("有新连接加入!当前在线人数为" getOnlineCount());
  34.  
    try {
  35.  
    MsgResponseVo userMsgResponseVo = new MsgResponseVo();
  36.  
    userMsgResponseVo.setMsg("SUCCESS");
  37.  
    WebSocketServer.sendInfo(JSON.toJSONString(userMsgResponseVo));
  38.  
    } catch (IOException e) {
  39.  
    log.error("websocket IO异常");
  40.  
    }
  41.  
    }
  42.  
     
  43.  
    /**
  44.  
    * 连接关闭调用的方法
  45.  
    */
  46.  
    @OnClose
  47.  
    public void onClose() {
  48.  
    //从set中删除
  49.  
    webSocketSet.remove(this);
  50.  
    //在线数减1
  51.  
    subOnlineCount();
  52.  
    log.info("有一连接关闭!当前在线人数为" getOnlineCount());
  53.  
    }
  54.  
     
  55.  
    /**
  56.  
    * 收到客户端消息后调用的方法
  57.  
    *
  58.  
    * @param message 客户端发送过来的消息
  59.  
    */
  60.  
    @OnMessage
  61.  
    public void onMessage(String message, Session session) {
  62.  
    log.info("来自客户端的消息:" message);
  63.  
     
  64.  
    //群发消息
  65.  
    for (WebSocketServer item : webSocketSet) {
  66.  
    try {
  67.  
    item.sendMessage(message);
  68.  
    } catch (IOException e) {
  69.  
    e.printStackTrace();
  70.  
    }
  71.  
    }
  72.  
    }
  73.  
     
  74.  
    /**
  75.  
    * @param session
  76.  
    * @param error
  77.  
    */
  78.  
    @OnError
  79.  
    public void onError(Session session, Throwable error) {
  80.  
    log.error("发生错误");
  81.  
    error.printStackTrace();
  82.  
    }
  83.  
     
  84.  
    public void sendMessage(String message) throws IOException {
  85.  
    this.session.getBasicRemote().sendText(message);
  86.  
    }
  87.  
     
  88.  
    /**
  89.  
    * 群发自定义消息
  90.  
    */
  91.  
    public static void sendInfo(String message) throws IOException {
  92.  
    log.info(message);
  93.  
    for (WebSocketServer item : webSocketSet) {
  94.  
    try {
  95.  
    item.sendMessage(message);
  96.  
    } catch (IOException e) {
  97.  
    continue;
  98.  
    }
  99.  
    }
  100.  
    }
  101.  
     
  102.  
    public static synchronized int getOnlineCount() {
  103.  
    return onlineCount;
  104.  
    }
  105.  
     
  106.  
    public static synchronized void addOnlineCount() {
  107.  
    WebSocketServer.onlineCount ;
  108.  
    }
  109.  
     
  110.  
    public static synchronized void subOnlineCount() {
  111.  
    WebSocketServer.onlineCount--;
  112.  
    }
  113.  
    }

3.3、创建测试发送消息接口

  1.  
    @GetMapping("/testWebSocket")
  2.  
    public ApiRestResponse testWebSocket() throws IOException {
  3.  
            //消息体
  4.  
    MsgResponseVo technicianMsgResponseVo = new MsgResponseVo();
  5.  
    technicianMsgResponseVo.setRole("Technician");
  6.  
    technicianMsgResponseVo.setRoleId(1);
  7.  
    technicianMsgResponseVo.setMsg("您的订单已取消");
  8.  
    technicianMsgResponseVo.setMsgStatus("CANCEL_ORDER");
  9.  
    technicianMsgResponseVo.setOrderNo("test");
  10.  
            //发送消息
  11.  
    WebSocketServer.sendInfo(JSON.toJSONString(technicianMsgResponseVo));
  12.  
    return ApiRestResponse.success();
  13.  
    }
  14.  
    }

3.4、测试webSocket(http://www.jsons.cn/websocket/

在网站中输入ws://ip:端口/webSocket工具类的前缀(ws://127.0.0.1:8080/websocket)

学新通

3.5、前端使用WebSocket监听后端WebSocket地址 ,接收到消息后做下一步业务处理。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgaejcc
系列文章
更多 icon
同类精品
更多 icon
继续加载