1.引入websocket.js到项目里,附上websocket.js代码
class Echo {
// // ws 服务地址
// public addr;
// // ws 要监听的事件
// public events;
// // 当前是否正在重联络
// public isRetrying;
// // ws 实例
// public ws;
// // 注册的 error 回调
// public errorCallback;
constructor() {
this.RETRY_COUNT = 10;
this.events = new Map();
this.isRetrying = false;
}
// 连接
connect(addr, successCallback, errorCallback) {
this.addr = addr;
this.successCallback = successCallback;
this.errorCallback = errorCallback;
this.ws = new WebSocket(this.addr);
this.ws.addEventListener("open", event => {
this.onOpen(event);
});
this.ws.addEventListener("message", event => {
this.onMessage(event);
});
this.ws.addEventListener("close", event => {
this.onClose(event);
});
this.ws.addEventListener("error", event => {
this.onError(event);
});
}
// open 回调
onOpen(event) {
console.log('链接成功',event);
this.successCallback();
}
// 收到消息
onMessage(event) {
const ECHO_ERROR = "echo.error";
// 后端返回消息类型为 {event:'',data:'{}'} 的json字符串
const message = JSON.parse(event.data);
if (message.event === ECHO_ERROR) {
return;
}
console.log('收到message消息',message);
this.trigger(message.event, message.data?JSON.parse(message.data):{});
}
// 连接关闭
onClose(event) {
// this.retry();
}
// 连接错误
onError(event) {
this.errorCallback && this.errorCallback("重新连接");
try {
this.retry();
} catch (err) {
console.log(err || event);
}
}
// 重连
retry() {
if (this.isRetrying) {
return;
}
if(this.RETRY_COUNT===0){
return;
}
this.RETRY_COUNT=this.RETRY_COUNT-1;
this.isRetrying = true;
setTimeout(() => {
// 重新实例化一个 ws
this.ws = new WebSocket(this.addr);
this.connection();
this.isRetrying = false;
}, 5000);
}
// 销毁此次长链接
destroy() {
console.log('销毁此次长链接');
console.log('sockerDestry');
this.ws.close();
this.ws.onmessage = null;
this.ws.onopen = null;
this.ws.onclose = null;
this.ws = null;
// delete this.ws;
}
// 添加事件监听
listen(event, callback) {
this.events.set(event, callback);
return this;
}
// 停止事件监听
stopListen(event) {
this.events.delete(event);
return this;
}
// 发出消息
emit(msg) {
this.ws.send(JSON.stringify(msg));
}
// 事件发生时执行相应的 callback
trigger(event, data) {
this.events.forEach((callback, key) => {
if (event === key) {
callback(data);
}
});
}
}
export default Echo;
2.配置,环境wsUrl:'wss://接口地址',
3.在vuex里做缓存,存储
import Echo from '@/utils/websocket.js';
import { wsUrl } from '@/config'
const state = {
wsClient: new Echo()
}
const mutations = {
setWsClient(state, wsClient){
state.wsClient = wsClient
},
}
const actions = {
// 设置websocket
wsClientConnect({ commit, state }, id) {
state.wsClient.connect(`${wsUrl}/${id}`,()=>{
commit('setWsClient', state.wsClient)
console.log('success')
},()=>{
console.log('error')
});
},
wsDestroy({ commit, state }){
state.wsClient.destroy();
}
}
export default {
namespaced:true,
state,
mutations,
actions
}
4.页面红点,需求,取值
userInfoStore(){
return this.$store.getters.userInfo
}
5.监听,是否已读
userId(value){
// 监听userid 进行websocket连接
this.$store.dispatch('websocket/wsClientConnect', value)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)