在实际vue项目中,我有一个接入服务端websocket的需求
调试了一段时间终于成功了,记录一下
1.配置ws
socket() { //socket()连接方法
let wssString = window.location.href.indexOf("/a") === -1 ? "wss:测试地址/ws" : "wss:正式地址/ws"
let ws = new WebSocket(wssString);
this.ws = Stomp.over(ws);
this.ws.heartbeat.outgoing = 1;
this.ws.heartbeat.incoming = 0;
this.ws.connect("root", "root", this.onConnected, this.onFailed);
},
onConnected() { //连接池
//订阅频道
//非正式版本下,加test-
const topic =
"后端给的地址" +
(window.location.href.indexOf("/a") === -1 ? "test-" : "") +
localData("get", "getUserInfo").id;
this.ws.subscribe(topic, this.responseCallback, this.onFailed); //失败需要重启
},
onFailed(frame) { // 失败后两秒重启
setTimeout(() => {
this.socket();
}, 2000);
},
2.配置响应函数
responseCallback(frame) {
//接收消息处理
if (JSON.parse(frame.body)) {
//你实际的操作
}
},
3.在mounted钩子中启动ws
mounted() {
setTimeout(() => {
this.socket();
}, 1000);
}