|
|
/*
|
|
|
* @Author: ch
|
|
|
* @Date: 2022-05-18 14:54:47
|
|
|
* @LastEditors: ch
|
|
|
* @LastEditTime: 2022-05-19 17:35:21
|
|
|
* @Description: file content
|
|
|
*/
|
|
|
|
|
|
export class MsbWebSktNew{
|
|
|
constructor(option) {
|
|
|
this.option = {
|
|
|
ioKey : 'traceId',
|
|
|
reconnect: true,
|
|
|
...option
|
|
|
}
|
|
|
this.socket = null;
|
|
|
this.queue = {};
|
|
|
this.hook = {};
|
|
|
|
|
|
this.sessionData = [];
|
|
|
this.curSession = {};
|
|
|
}
|
|
|
/**
|
|
|
* 创建连接返回一个Promise 创建成功并成功打开连接算连接成功
|
|
|
* @param {*} option
|
|
|
*/
|
|
|
connect(option) {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
this.socket = uni.connectSocket({
|
|
|
...option,
|
|
|
fail(e){
|
|
|
reject(e);
|
|
|
}
|
|
|
});
|
|
|
this.socket.onOpen(() => {
|
|
|
this.socket.onMessage((res) => {
|
|
|
const result = JSON.parse(res.data);
|
|
|
// 每次消息推送都会推送至onMessage Hook中
|
|
|
this.hook.onMessage && this.hook.onMessage(result);
|
|
|
|
|
|
// 查看是否有返回信息处理Hook,有的话优先取处理后的结果返回
|
|
|
const responseData = this.hook.onResponse ? this.hook.onResponse(result) : result;
|
|
|
const isError = responseData.constructor === Promise;
|
|
|
// 如果再消息堆里有此消息回调,则执行回调,并删除
|
|
|
const cbk = this.queue[result[this.option.ioKey]];
|
|
|
if (cbk) {
|
|
|
cbk(isError ? {error:responseData} : {result:responseData});
|
|
|
delete this.queue[result[this.option.ioKey]];
|
|
|
}
|
|
|
})
|
|
|
resolve(this.socket);
|
|
|
});
|
|
|
this.socket.onClose(() => {
|
|
|
if (this.option.reconnect) {
|
|
|
this.connect();
|
|
|
}
|
|
|
});
|
|
|
});
|
|
|
}
|
|
|
/**
|
|
|
* 向服务端发送消息||请求,返回一个Promise对象,收到ioKey对应的消息会算一个同步完成
|
|
|
* @param {*} data
|
|
|
*/
|
|
|
send(data) {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
this.queue[data[this.option.ioKey]] = ({ result, error }) => {
|
|
|
if (result) {
|
|
|
resolve(result);
|
|
|
} else {
|
|
|
reject(error);
|
|
|
}
|
|
|
};
|
|
|
this.socket.send({
|
|
|
data : JSON.stringify(data),
|
|
|
fail(e) {
|
|
|
if (this.hook.onResponse) {
|
|
|
reject(this.hook.onResponse(e))
|
|
|
}
|
|
|
reject(e);
|
|
|
}
|
|
|
});
|
|
|
})
|
|
|
}
|
|
|
/**
|
|
|
* 扩展钩子
|
|
|
* @param {*} hookName
|
|
|
* @param {*} cb
|
|
|
*/
|
|
|
use(hookName, cb){
|
|
|
this.hook[hookName] = cb;
|
|
|
}
|
|
|
|
|
|
|
|
|
} |