vwebsocket
1、真正意义上的全双工;一次连接可保持与后端长期连接进行数据交互;可以互相主动请求信息(客户端可向后端请求信息,后端可主动推送消息到前端)
2、存在大量求情数据接口的场景下,具有明显的性能优势;能够节省网络宽带的消耗
export default{
data(){
return {
websocket:null,
}
},
created(){
this.initWebsocket();
}
methods: {
initWebSocket() {
const url = "wss:wss.xxxxxxx.com:8282";
this.websocket = new WebSocket(url);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websocket.onmessage = this.websocketonmessage;
this.websocket.onclose = this.websocketclose;
},
websocketonopen() {
console.log("WebSocket连接成功");
let data = {};
this.websocket.send(
JSON.stringify(data)
);
},
websocketonerror(e) {
console.log("WebSocket连接发生错误");
// 错误重连
this.initWebSocket()
},
websocketonmessage(e) {
//数据接收
const that = this;
const data = JSON.parse(e.data);
console.log('接受数据',data);
},
websocketsend(agentData) {
//数据发送
this.websocket.send(agentData);
},
websocketclose(e) {
//关闭
console.log("websocket close : " + e);
},
},
}