这是在vue中的使用,JQ也可以使用,只需要修改成JQ语法就行
initWebSocket(){ //初始化weosocket
let userID = sessionStorage.getItem(‘userInfo’);
const wsuri = “ws://test1.pengchangke.com.cn:30007/boss/”+userID;//ws地址
// 创建websocket连接
this.websock = new WebSocket(wsuri);
// 监听打开
this.websock.onopen= this.websocketonopen;
// 监听关闭
this.websock.onclose = this.websocketclose;
//监听异常
this.websock.onerror = this.websocketonerror;
//监听服务器发送的消息
this.websock.onmessage = this.websocketonmessage;
},
websocketonopen(e) {
console.log(“WebSocket连接成功”,e);
},
websocketonerror(e) { //错误
console.log(“WebSocket连接发生错误”,e);
},
websocketonmessage(e){ //数据接收
// const redata = JSON.parse(e.data);
//注意:长连接我们是后台直接1秒推送一条数据,
//但是点击某个列表时,会发送给后台一个标识,后台根据此标识返回相对应的数据,
//这个时候数据就只能从一个出口出,所以让后台加了一个键,例如键为1时,是每隔1秒推送的数据,为2时是发送标识后再推送的数据,以作区分
console.log(“数据接收:”,e);
},
websocketsend(agentData){//数据发送
this.websock.send(agentData);
},
websocketclose(e){ //关闭
console.log(“链接关闭(” + e+ “)”);
},