zoukankan      html  css  js  c++  java
  • SpringBoot如何使用WebSocket实现前后端交互?

    背景

    我们都知道http协议只能在浏览器单方面向服务器发起请求时获得响应,然而服务器不能主动向浏览器推送消息,想要实现浏览器的主动推送目前有两种主流的实现方式:

    • 轮询:缺点很多,但是实现简单
    • websocket: 在浏览器和服务器之间建立TCP连接,实现全双工通信
      springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议。本篇讲述如何使用springboot实现简单的websocket。

    实现

    一、导入依赖

    直接在pom.xml中导入依赖。

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

    二、新建WebSocket配置类,注入Bean

    首先注入一个ServerEndpointExporterBean,该Bean会自动注册使用@ServerEndpoint注解申请的websocket endpoint,代码如下:

    @Component
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }
    

    三、新建WebSocket服务端,在其中处理websocket逻辑

    @Component  //注册到容器中
    @ServerEndpoint("/webSocket")  //接收websocket请求路径
    @Slf4j
    public class WebSocket {
        //当前连接(每个websocket连入都会创建一个WebSocket实例)
        private Session session;
    
        //定义一个websocket容器存储session,即存放所有在线的socket连接
        private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    
        //处理连接建立
        @OnOpen
        public void opOpen(Session session){
            this.session = session;
            log.info("【有新的客户端连接了】:{}",session.getId());
            webSocketSet.add(this);  //将新用户加入在线组
            log.info("【websocket消息】有新的连接,总数:{}",webSocketSet.size());
        }
    
        //处理连接关闭
        @OnClose
        public void Onclose(){
            webSocketSet.remove(this);
            log.info("【websocket消息】连接断开,总数:{}",webSocketSet.size());
        }
    
        //接受消息
        @OnMessage
        public void onMessage(String message){
            log.info("【websocket消息】收到客户端发来的消息:{}",message);
        }
    
        // 群发消息
        public void sendMessage(String message) {
            for (WebSocket webSocket : webSocketSet) {
                log.info("【websocket消息】广播群发消息,message={}",message);
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    

    四、客户端实现,可以借助FreeMarker模板工具直接写在ftl文件里。

    由于部分浏览器可能不支持,可以先测试,代码如下:

    <script>
        var websocket = null;
        if('WebSocket' in window){
            websocket = new WebSocket('ws://localhost:8080/webSocket');
        }else{
            alert('当前浏览器不支持websocket消息通知');
        }
    
        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            console.log("ws建立连接成功");
        }
    
        //连接关闭的回调方法
        websocket.onclose = function (event) {
            console.log("ws连接关闭");
        }
    
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            /*setMessageInnerHTML(event.data);*/
           // alert("ws接收返回消息:"+event.data);
            console.log("服务器返回消息: " + event.data);
            //弹窗提醒(要用到JQuary,所以要先引入JQuary)   播放音乐
            $('#mymodal').modal('show')
        }
    
        //连接发生错误的回调方法
        websocket.onerror = function(event){
            alert('websocket通信发生错误!')
        }
    
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function() {
            websocket.close();
        }
        </script>
    

    五、测试(项目实现客户创建新订单之后,前台发出提醒)

    @Autowired
    private WebSocket webSocket;
    
    @Override
        @Transactional
        public OrderDTO create(OrderDTO orderDTO) {//创建订单
            。。。。(具体代码省略)
    
           //创建新订单  发送websocket消息
            webSocket.sendMessage(orderDTO.getOrderId());
            return orderDTO;
        }
    

    添加新订单:

    接收到websocket消息

  • 相关阅读:
    day 34
    day 33 线程锁
    day 32 操作系统、线程和进程(GIL锁)
    day 31 网络基础的补充
    day 30 多线程 socketserver模块补充
    python自学笔记 2019/07/01
    类与对象的概念
    递归及三种二分法
    好看的颜色
    zend 汉化
  • 原文地址:https://www.cnblogs.com/xiaozhengtongxue/p/13448778.html
Copyright © 2011-2022 走看看