什么叫websocket:我的理解就是一个特殊的后端接口,只不过这个后端接口不是通过前端点击什么然后去请求后端接口数据。而是进入一个界面以后就一直与这个接口相连接了。只不过没有数据传输过来。只有当后端通过这个接口传输数据时,前端才能够接受:
代码如下:
事先引入需求模块
import SockJS from "sockjs-client";
import Stomp from "stompjs";
/* 建立stomp连接,监听报警消息 */ createStomp() { const socket = new SockJS(ScheduleApi['CHECK_SOCKJS_URL']); // socket.onopen = function(e) { console.log('open'); } // socket.onmessage = function(e) { console.log(e.data); } // return // 经过stomp.over之后,会重写onopen之类的方法 const client = Stomp.over(socket); // 屏蔽stomp的debug信息 client.debug = function(str) { // console.log('%c'+str, 'color: BlueViolet'); }; this.stompClient = client; client.connect({}, _ => { client.subscribe(ScheduleApi['CHECK_STOMP_TOPIC'], msg => { // console.log('Stomp', msg); let { body:jsonData } = msg; let data; try { data = JSON.parse(jsonData); } catch(e) { console.log('%c报警stomp,json格式不对', 'color: BlueViolet'); return; } }); }); }, /* 销毁stomp连接 */ destroyStomp() { this.stompClient && this.stompClient.disconnect(); },