WebSocket vue连接、客户端主动关闭实例
https://blog.csdn.net/WK313753744/article/details/56007028
https://blog.csdn.net/ll666634/article/details/79028930
用vue-cli搭建的项目 在common下新建个js文件内容如下:
export function initWebpack(token){//初始化websocket
const wsuri = 'ws://'+webUrl+'?token='+token;
this.websock = new WebSocket(wsuri);//这里面的this都指向vue
console.log(this.websock)
this.websock.onopen = websocketopen;
this.websock.onmessage = websocketonmessage;
this.websock.onclose = websocketclose;
this.websock.onerror = websocketerror;
}
function websocketopen(){//打开
console.log("WebSocket连接成功")
}
function websocketonmessage(e){ //数据接收
console.log("WebSocket接受到数据")
if(sessionStorage.getItem('number')==undefined){
this.number = 1
//存session
resetSetItem('number',this.number);
}else if(sessionStorage.getItem('number')){
var num = parseInt(sessionStorage.getItem('number'))
num+=1
//存session
resetSetItem('number',num);
}
}
function websocketclose(){ //关闭
console.log("WebSocket关闭");
// initWebpack(this.token)
}
function websocketerror(){ //失败
console.log("WebSocket连接失败");
}
export function close(){
this.websock.close()//关闭websocket
this.websock.onclose=function(e){
console.log(e)//监听关闭事件
console.log('关闭')
}
}
接受的数据我存session里面了 所以我在message里面添加几句代码
如果想刷新重新链接websocket 可以在App.vue页面里添加个钩子函数
客户端主动关闭websocket 在关闭的地方触发函数就行 web是import引入的开头的js文件