websocket 刷新网页 重连不上,如何操作
initSocket() {
// 有参数的情况下:
let url = "ws://xxx";
// 没有参数的情况:接口
// let url1 = 'ws://localhost:9998'
this.webSocket = new WebSocket(url);
this.webSocket.onopen = this.webSocketOnOpen;
this.webSocket.onclose = this.webSocketOnClose;
this.webSocket.onmessage = this.webSocketOnMessage;
this.webSocket.onerror = this.webSocketOnError;
},
// 建立连接成功后的状态
webSocketOnOpen() {
console.log("websocket连接成功");
this.webSocket.send("111");
},
// 获取到后台消息的事件,操作数据的代码在onmessage中书写
webSocketOnMessage(res) {
// res就是后台实时传过来的数据
console.log(res);
//给后台发送数据
this.webSocket.send("111");
},
// 关闭连接
webSocketOnClose() {
// this.webSocket.close();
console.log("websocket连接已关闭");
},
//连接失败的事件
webSocketOnError(res) {
console.log("websocket连接失败");
this.webSocket.close();
// 打印失败的数据
console.log(res);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…