webSocket + springboot+vue3用法

领导安排个任务,大屏显示数据,要与后台数据一致,所以用到了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);

};

相关推荐
AALoveTouch2 小时前
网球馆自动预约系统的反调试
javascript·网络
一个响当当的名号3 小时前
一些主要应用和NAT
运维·服务器·网络
洋葱圈儿6665 小时前
nat静态地址转化
网络·智能路由器
OPTree4125 小时前
H3C网络设备 实验三: 搭建两个局域网,使两个局域网相互通信(路由器,自动分配ip,DHCP协议)
网络·tcp/ip·智能路由器
WTCLLB5 小时前
netgear r6220 路由器,刷openwrt后,系统备份还原
linux·网络·智能路由器·openwrt
做运维的阿瑞6 小时前
Linux系统性能监控与故障定位实战:CPU/内存/I/O/网络
linux·运维·网络
CiLerLinux6 小时前
第五十二章 ESP32S3 UDP 实验
网络·单片机·嵌入式硬件·网络协议·udp
切糕师学AI7 小时前
P2P技术
网络·网络协议·p2p
尤利乌斯.X8 小时前
复杂网络仿真从入门到精通:0 学习路线
网络·学习·matlab·仿真·复杂网络
Chandler249 小时前
一图掌握 网络协议 核心要点
网络协议·tcp/ip·计算机网络·http