webSocket + springboot+vue3用法

本文介绍了如何在SpringBoot项目中利用WebSocket技术实现实时数据传输,包括添加WebSocket依赖、配置WebSocketConfig、编写WebSocket类及其解码和编码器,以及前端如何连接和接收后端推送的数据。
摘要由CSDN通过智能技术生成

领导安排个任务,大屏显示数据,要与后台数据一致,所以用到了websocket,涉及的前后端代码整理如下,希望对大家有所帮助。

后端代码

pom文件添加依赖

<!--websocket依赖-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
   <version>2.7.0</version>
</dependency>

Java  WebSocketConfig 配置文件

package com.example.only.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.ServletRequestListener;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements ServletRequestListener {

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

}
WebSocket类 通用方法,这里因为大屏项目,没有登入的id,就没有加id验证
package com.example.only.common;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/webSocket",decoders = { warningDecoder.class }, encoders = { warningEncoder.class })
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new                                  CopyOnWriteArraySet<WebSocket>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSockets.add(this);
        System.out.println("连接成功");
    }

    @OnClose
    public void onClose(Session session){
        webSockets.remove(this);
        System.out.println("连接关闭");
    }

    @OnMessage
    public  void message(String message,Session session) {
        System.out.println("【WebSocket消息】收到客户端发来的消息:{}"+message);
    }

    //实现服务器主动推送(业务层不要调用这个方法,调用sendInfo)
    public void sendMseeage(Object object) throws IOException, EncodeException {
        System.out.println(object.toString())
        this.session.getBasicRemote().sendObject(object);
    }

    //群发(或者单发)自定义消息,最终调用的方法
    public void sendInfo(Object object) throws Exception{
                for (WebSocket webSocket:webSockets) {
                    webSocket.sendMseeage(object);
        }
    }
}

warningDecoder 解码器类

package com.example.only.common;

import com.alibaba.fastjson.JSON;

import javax.websocket.DecodeException;
import javax.websocket.EndpointConfig;


public class warningDecoder implements javax.websocket.Decoder.Text<Object> {
/*
 * 解码类
 * 
 * */
   @Override
   public void destroy() {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void init(EndpointConfig arg0) {
      // TODO Auto-generated method stub
      
   }

   @Override
   public Object decode(String string) throws DecodeException {
      return     JSON.parseObject(string, Object.class);
   }

   @Override
   public boolean willDecode(String arg0) {
      return true;
   }

}

warningEncoder编码器类

package com.example.only.common;

import com.alibaba.fastjson.JSON;

import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;


public class warningEncoder implements javax.websocket.Encoder.Text<Object> {
/*
 * 编码器
 * 
 * */
   @Override
   public void destroy() {
      // TODO Auto-generated method stub

   }

   @Override
   public void init(EndpointConfig arg0) {
      // TODO Auto-generated method stub

   }

   @Override
   public String encode(Object obj) throws EncodeException {
      return JSON.toJSONString(obj);
   }


}

测试类:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(method = {POST, GET}, value = "/admin/test")
public class Test {
    @Autowired
    private WebSocket webSocket;
    @RequestMapping("/send")
    public void send(
        @RequestParam(value = "olv")String olv
    ) throws Exception {
       webSocket.sendInfo(olv);
    }
}

前端代码:

const initWebSocket = () => {
  var websocket = null;
  if ("WebSocket" in window) {

   // 后端代码的地址+端口号
    websocket = new WebSocket("ws://ip:端口号/webSocket");
  } else {
    alert("该浏览器不支持websocket!");
  }
  websocket.onopen = function (event) {
    console.log("建立连接");
    websocket.send("Hello WebSockets!");
  };
  websocket.onclose = function (event) {
    console.log("连接关闭");
    reconnect(); //尝试重连websocket
  };
  //建立通信后,监听到后端的数据传递
  websocket.onmessage = function (event) {
    console.log(event);
   
  };
  websocket.onerror = function () {
    // notify.warn("websocket通信发生错误!");
    // initWebSocket()
  };
  window.onbeforeunload = function () {
    websocket.close();
  };
};
// 重连
const reconnect = () => {
  console.log("正在重连");
  // 进行重连
  setTimeout(function () {
    initWebSocket();
  }, 1000);
};

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值