websocket不同于http协议,是由后端往前端推送数据,因此对于即时性数据比较合适。
创建websocket:
let base = config.wsIp;**
let webSocketIP = ``;
let socket = '';
let isFirst = true;
export const createSocket =tid => {
isFirst = true;
console.log('establish websocket connection')
webSocketIP = `${base}/websocket/${tid}`
socket = new WebSocket(webSocketIP);
socket.onopen = onopenWs;
socket.onclose = oncloseWs;
socket.onerror = onerrorWs;
socket.onmessage = onmessageWs;
}
const onopenWs = event => {
console.log("链接", event);
socket.send("websocket client connect testss");
}
const oncloseWs = event => {
console.log("断开链接", event);
clearInterval(setIntervalWesocketPush)
}
const onerrorWs = event => {
console.log("出现错误", event);
clearInterval(setIntervalWesocketPush)
}
const onmessageWs = event => {
console.log(JSON.parse(event.data))
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: event,
isFirst: isFirst
}
}))
if(isFirst) {
isFirst = false;
}
}
使用:
import { createSocket } from '../apis/websocket'
this.getNoticeData(this.tid);
getNoticeData(tid) {
createSocket(tid);
window.addEventListener('onmessageWS', this.setNoticeData)
},
这种写法是参考的简书上的一个老哥的,但他那个里边有点问题,所以简单做了修改。修改主要是去除了前端的每隔一定时间请求一下,这是没必要的,后端定时推送数据本身就是websocket的一大优势,如果使用前端每隔一段时间请求一下,那还不如直接使用http请求那。