1:前端代码如下
首先项目中需要引入websocket
// WebSocket对象方法getWebSocket(){// 创建一个 websocket 连接var ws = new WebSocket("ws://10.66.78.118:8085/api/cloud/ws");// websocket 创建成功事件ws.onopen = function (event) {window.setInterval(function ping() {ws.send('Hello, WebSocket!'); // 发送一条消息console.log('已发送消息');}, 10000);console.log('WebSocket连接成功',event);};// websocket 接收到消息事件ws.onmessage = function (e) {const messageContent = JSON.parse(e.data);console.log('收到消息:', messageContent);var msg = JSON.parse(e.data);console.log(msg,'消息事件')}// 关闭ws.onclose = function close() {console.log('Disconnected');};// websocket 错误事件ws.onerror = function (error) {console.error('WebSocket error observed:', error);};}
2.在页面初始化的时候调用getWebSocket此方法