2 回答

TA貢獻1951條經驗 獲得超3個贊
// 每一個實例都只能open一條socket線路,用鎖機制防止重復open
// 本例中不使用心跳檢測,為了方便,只要close是非主動觸發(fā)且前端能捕捉到的(如瀏覽器主動斷開,服務器主動斷開),都會進行自動重連
export default class MyWebSocket {
constructor(url) {
this.url = url;
// close來源判斷及后續(xù)操作
this.closeConfig = {
resolve: null,
closing: false
}
// promise池
this.promisePool = {};
}
tokenCheck(req, rsp) {
// 此處根據自己的數(shù)據結構進行tokenCheck的判斷,返回一個boolean
}
open() {
return new Promise((resolve, reject) => {
if (typeof this._websocket === 'undefined') {
this._websocket = new WebSocket(this.url);
this._websocke.open = (e) => {
resolve({e, ws: this});
};
this._websocket.onerror = (e) => {
reject(e);
}
}
this._websocket.onclose = (e) => {
// 非主動close
if (!this.closeConfig.closing) {
console.log('reconnect');
// 對應的重連操作
}
// 若手動close,恢復初始狀態(tài)
this.closeConfig.closing = false;
}
this._websocket.onmessage = (e) => {
const key = e.content.token;
const req = this.promisePool[key]
req.resolve(e);
delete this.promisePool[key];
};
});
}
close() {
this.closeConfig.closing = true;
this._websocket.close();
}
// token包含在content中
send(name, content) {
return new Promise((resolve, reject) => {
this.promisePool[content.token] = {
content,
resolve,
reject,
name
};
this._websocket.send({name, content});
});
}

TA貢獻1886條經驗 獲得超2個贊
function getMsg() {
return new Promise((resolve, reject) => {
ws.onmessage = (e) => {
resloce(e)
}
})
}
getMsg.then(res => {
// dosomething
})
添加回答
舉報