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);

};

相关推荐
m0_5695310124 分钟前
《K8s 网络入门到进阶:Service 与 Ingress 原理、部署方案及核心区别对比》
网络·容器·kubernetes
广东大榕树信息科技有限公司25 分钟前
当运维管理面临挑战时,如何借助动环监控系统提升响应能力?
运维·网络·物联网·国产动环监控系统·动环监控系统
北京耐用通信31 分钟前
耐达讯自动化网关:用Profinet唤醒沉睡的DeviceNet流量计,省下60%改造费!
人工智能·科技·物联网·网络协议·自动化·信息与通信
狂奔的sherry2 小时前
WIFI后端功能问题解决
网络
yimengsama2 小时前
VMWare虚拟机如何连接U盘
linux·运维·服务器·网络·windows·经验分享·远程工作
Running_slave2 小时前
聊聊TCP滑窗的一些有趣“病症”
前端·网络协议·tcp/ip
Xの哲學2 小时前
Linux NAT 深度剖析: 从设计哲学到实现细节
linux·服务器·网络·架构·边缘计算
鲨莎分不晴2 小时前
强化学习第七课 —— 策略网络设计指南:赋予 Agent“大脑”的艺术
网络·人工智能·机器学习
胡闹542 小时前
海康和大华厂商的RTSP取流地址格式进行拉流直播
java·网络
想用offer打牌3 小时前
一站式了解跨域问题
网络协议·面试·架构