领导安排个任务,大屏显示数据,要与后台数据一致,所以用到了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 {@Beanpublic 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>();@OnOpenpublic void onOpen(Session session){this.session = session;webSockets.add(this);System.out.println("连接成功");}@OnClosepublic void onClose(Session session){webSockets.remove(this);System.out.println("连接关闭");}@OnMessagepublic 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> { /** 解码类* * */@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void init(EndpointConfig arg0) {// TODO Auto-generated method stub}@Overridepublic Object decode(String string) throws DecodeException {return JSON.parseObject(string, Object.class);}@Overridepublic 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> { /** 编码器* * */@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void init(EndpointConfig arg0) {// TODO Auto-generated method stub}@Overridepublic 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 {@Autowiredprivate 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);
};