sdk封装接口调整、接口文档调整

This commit is contained in:
zhuhailiang 2023-11-01 10:23:40 +08:00
parent ce2377c72b
commit a9909a4039
2 changed files with 473 additions and 512 deletions

View File

@ -7,43 +7,47 @@
### 1.0连接服务器 ### 1.0连接服务器
初始化完成后,调用连接服务器 初始化完成后,调用连接服务器
```javascript ```javascript
const uniSocket new UniSocket({ const uniSocket = new UniSocket({
url: 'websocketUrl' url: 'websocketUrl'
}); });
``` ```
### 1.1绑定账号 ### 1.1绑定账号
在页面定义 function sendBufferRegister
当socket连接成功回调然后绑定用户ID 当socket连接成功回调然后绑定用户ID
```javascript ```javascript
uniSocket.sendBufferRegister() uniSocket.on('connectioned', function() {
uniSocket.bindAccount(id)
}, true)
``` ```
### 1.2绑定会议房间号
### 1.2接收消息 当socket连接成功回调然后绑定用户ID
在页面定义function emitToClientAllEvent 当收到服务端发送的消息时回调 ```javascript
uniSocket.sendBufferTag(tag) // 会议结束删除房间号传null或者空
```
### 1.3接收消息
```javascript ```javascript
uniSocket.on('*', async (message) => { uniSocket.on('*', async (message) => {
}) })
``` ```
### 1.3停止接收消息 ### 1.4停止接收消息
停止接受推送,将会退出当前账号登录,端口与服务端的连接 停止接受推送,将会退出当前账号登录,端口与服务端的连接
```javascript ```javascript
uniSocket.close(); uniSocket.close();
``` ```
### 1.4恢复接收消息 ### 1.5恢复接收消息
重新恢复接收推送,重新连接服务端,并登录当前账号 重新恢复接收推送,重新连接服务端,并登录当前账号
```javascript ```javascript
uniSocket.reconnection(); uniSocket.reconnection();
``` ```
### 1.5发送SentBody请求 ### 1.6发送SentBody请求
支持通过长连接发送一个异步请求到服务的进行处理 支持通过长连接发送一个异步请求到服务的进行处理
例如发送一个位置上报请求 例如发送一个位置上报请求
key client_cycle_location 需要在服务端创建一个实现的handler参照BindHandler key client_cycle_location 需要在服务端创建一个实现的handler参照BindHandler
#### 1.5.1 protobuf序列化 #### 1.6.1 protobuf序列化
```javascript ```javascript
const SENT_BODY = 3 const SENT_BODY = 3
var body = new proto.com.farsunset.cim.sdk.web.model.SentBody(); var body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
@ -52,21 +56,10 @@ body.getDataMap().set("uid","10000");
body.getDataMap().set("latitude","123.82455"); body.getDataMap().set("latitude","123.82455");
body.getDataMap().set("longitude","412.245645"); body.getDataMap().set("longitude","412.245645");
body.getDataMap().set("location","上海市徐汇区云景路8弄"); body.getDataMap().set("location","上海市徐汇区云景路8弄");
let data = body.serializeBinary(); uniSocket.sendRequest(body)
let protobuf = new Uint8Array(data.length + 1);
protobuf[0] = SENT_BODY;
protobuf.set(data, 1);
const buffer = protobuf
this.uniSocket.send({
data: buffer,
success: (res) => {
// console.log(res)
console.log('成功')
},
});
``` ```
#### 1.5.2 json序列化 #### 1.6.2 json序列化
```javascript ```javascript
let body = {}; let body = {};
body.key ="client_cycle_location"; body.key ="client_cycle_location";
@ -76,17 +69,5 @@ body.data.uid = 10000;
body.data.latitude = 123.82455; body.data.latitude = 123.82455;
body.data.longitude = 412.245645; body.data.longitude = 412.245645;
body.data.location = "上海市徐汇区云景路8弄"; body.data.location = "上海市徐汇区云景路8弄";
uniSocket.sendRequest(body)
let data = body.serializeBinary();
let protobuf = new Uint8Array(data.length + 1);
protobuf[0] = SENT_BODY;
protobuf.set(data, 1);
const buffer = protobuf
this.uniSocket.send({
data: buffer,
success: (res) => {
// console.log(res)
console.log('成功')
},
});
``` ```

View File

@ -7,7 +7,6 @@
import "./message.js"; import "./message.js";
import "./replybody.js"; import "./replybody.js";
import "./sentbody.js"; import "./sentbody.js";
import store from '@/store'
let APP_VERSION = "1.0.0"; let APP_VERSION = "1.0.0";
let APP_CHANNEL = 'app' let APP_CHANNEL = 'app'
const APP_PACKAGE = "com.farsunset.cim"; const APP_PACKAGE = "com.farsunset.cim";
@ -19,513 +18,494 @@ const PONG = 0;
const DATA_HEADER_LENGTH = 1; const DATA_HEADER_LENGTH = 1;
const PONG_BODY = new Uint8Array([80, 79, 78, 71]); const PONG_BODY = new Uint8Array([80, 79, 78, 71]);
export default class Socket { export default class Socket {
constructor(option = {}) { constructor(option = {}) {
this.globalData = getApp().globalData this._url = option.url;
// console.log(this.globalData) // 是否设置重新连接
this._url = option.url; this._reconnection = option.reconnection || true;
// 是否设置重新连接 // 是否建立缓存池,默认true如果建立缓存池会将因为程序错误导致未发送成功的消息发送
this._reconnection = option.reconnection || true; this._buffer = option.buffer || true;
// 是否建立缓存池,默认true如果建立缓存池会将因为程序错误导致未发送成功的消息发送 /// on方法注册的事件
this._buffer = option.buffer || true; this.on_register = {};
/// on方法注册的事件 // 是否已成功连接
this.on_register = {}; this._connectioned = false;
// 是否已成功连接 // 缓存池
this._connectioned = false; this._buffer_register = [];
// 缓存池 // 发送缓存池的数据
this._buffer_register = []; this._auto_emit_buffer_data = option.autoEmitBuffer || false;
// 发送缓存池的数据 // 被动断开
this._auto_emit_buffer_data = option.autoEmitBuffer || false; this.closed = false;
// 被动断开 // 开始重连
this.closed = false; this.begin_reconnection = false;
// 开始重连 // 多少毫秒发送一次心跳
this.begin_reconnection = false; this._heart_rate = option.heartRate > 0 ? option.heartRate : 60000;
// 多少毫秒发送一次心跳 // 后端心跳字段
this._heart_rate = option.heartRate > 0 ? option.heartRate : 60000; this._heart_rate_type = option.heartRateType || "HEARTBEAT";
// 后端心跳字段 this.init();
this._heart_rate_type = option.heartRateType || "HEARTBEAT"; }
this.init();
}
/** /**
* 注册一个事件 * 注册一个事件
* @param {Object} event 事件 * @param {Object} event 事件
* @param {Object} handler 事件处理者 * @param {Object} handler 事件处理者
* @param {Boolean} single 此handler是否只处理一次 * @param {Boolean} single 此handler是否只处理一次
*/ */
async on(event, handler, single = false) { async on(event, handler, single = false) {
const eType = await this.getType(event); const eType = await this.getType(event);
if (eType === "[object String]" && eType.trim() !== "") { if (eType === "[object String]" && eType.trim() !== "") {
if (this.on_register[event] == void 0) { if (this.on_register[event] == void 0) {
this.on_register[event] = []; this.on_register[event] = [];
} }
if (single) { if (single) {
console.log('this.on_register[event]: ', this.on_register[event].length); console.log('this.on_register[event]: ', this.on_register[event].length);
for (let i = 0; i < this.on_register[event].length; i++) { for (let i = 0; i < this.on_register[event].length; i++) {
console.log(handler === this.on_register[event][i]); console.log(handler === this.on_register[event][i]);
if (handler === this.on_register[event][i]) { if (handler === this.on_register[event][i]) {
console.log('触发错误'); console.log('触发错误');
throw new UniSocketError(`当前「${event}」事件已被注册...`); throw new UniSocketError(`当前「${event}」事件已被注册...`);
} }
} }
} }
// 注册事件 // 注册事件
this.on_register[event.trim()].push(handler); this.on_register[event.trim()].push(handler);
} }
} }
/** /**
* 移除指定注册的事件 * 移除指定注册的事件
* @param {Object} name 事件名称 * @param {Object} name 事件名称
*/ */
async removeEventByName(name) { async removeEventByName(name) {
return Promise.then(() => { return Promise.then(() => {
delete this.on_register[name]; delete this.on_register[name];
}); });
} }
/** /**
* 给缓存池添加记录 * 给缓存池添加记录
*/ */
async addBuffer(data = {}) { async addBuffer(data = {}) {
const da = JSON.stringify(data); const da = JSON.stringify(data);
this._buffer_register.push(data); this._buffer_register.push(data);
} }
/** /**
* 获取缓存池 * 获取缓存池
*/ */
async getBuffer() { async getBuffer() {
return this._buffer_register; return this._buffer_register;
} }
/** /**
* 获取连接状态 * 获取连接状态
* @return {number} 0 表示连接中1表示连接成功2表示重连中3表示失败 * @return {number} 0 表示连接中1表示连接成功2表示重连中3表示失败
*/ */
async getState() { async getState() {
return this.begin_reconnection ? 2 : this._connectioned ? 1 : this.isError ? 3 : 0; return this.begin_reconnection ? 2 : this._connectioned ? 1 : this.isError ? 3 : 0;
} }
/** /**
* 关闭当前socket * 关闭当前socket
*/ */
async close() { async close() {
this.closed = true; this.closed = true;
this.SocketTask && this._connectioned && this.SocketTask.close(); this.SocketTask && this._connectioned && this.SocketTask.close();
} }
/** /**
* 发送消息 * 发送消息
*/ */
async emit(event, data = {}) { async emit(event, data = {}) {
if ( if (
this.getType(event) === "[object Object]" && this.getType(event) === "[object Object]" &&
this.getType(event) === "[object String]" this.getType(event) === "[object String]"
) { ) {
let e = data; let e = data;
data = event; data = event;
event = e; event = e;
} }
if (this.SocketTask) { if (this.SocketTask) {
const da = { const da = {
type: event, type: event,
data: data, data: data,
}; };
this.SocketTask.send({ this.SocketTask.send({
data: JSON.stringify(da), data: JSON.stringify(da),
fail: (e) => { fail: (e) => {
// 消息发送失败时将消息缓存 // 消息发送失败时将消息缓存
this.addBuffer(da); this.addBuffer(da);
throw new UniSocketError("Failed to send message to server... " + e); throw new UniSocketError("Failed to send message to server... " + e);
}, },
}); });
} else { } else {
throw new UniSocketError("The socket is not initialization or connection error!"); throw new UniSocketError("The socket is not initialization or connection error!");
} }
} }
/** // 绑定账号
* 将缓存池的数据发送 bindAccount(account) {
*/ console.log(account)
async sendBufferRegister() { if (this._connectioned) {
const tag = this.globalData.tag // 缓存池备份
if (this._connectioned) { let browser = {
// 缓存池备份 name: "Other",
let browser = { version: "1.0.0",
name: "Other", appLanguage: 'zh-CN'
version: "1.0.0", };
appLanguage: 'zh-CN' uni.getSystemInfo({
}; success: (res) => {
uni.getSystemInfo({ APP_VERSION = res.appVersion
success: (res) => { browser.version = res.osVersion
// console.log(res) browser.name = res.osName
APP_VERSION = res.appVersion browser.appLanguage = res.appLanguage
browser.version = res.osVersion if (res.uniPlatform === 'web') {
browser.name = res.osName APP_CHANNEL = 'uni-h5'
browser.appLanguage = res.appLanguage browser.version = res.hostVersion
if(res.uniPlatform === 'web') { browser.name = res.hostName
APP_CHANNEL = 'uni-h5' } else {
browser.version = res.hostVersion if (res.osName === "android") {
browser.name = res.hostName APP_CHANNEL = 'uni-android'
} else { }
if(res.osName === "android") { if (res.osName === "ios") {
APP_CHANNEL = 'uni-android' APP_CHANNEL = 'uni-ios'
} }
if(res.osName === "ios") { }
APP_CHANNEL = 'uni-ios' }
} });
}
}
});
// '绑定账号' APP_CHANNEL
let account = String(store.getters.user.id)
uni.setStorageSync('account', account)
let deviceId = uni.getStorageSync('deviceId')
if (deviceId == "" || deviceId == undefined) {
deviceId = this.generateUUID();
uni.setStorageSync('deviceId', deviceId)
}
let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
body.setKey("client_bind");
body.setTimestamp(new Date().getTime());
body.getDataMap().set("uid", account);
body.getDataMap().set("channel", APP_CHANNEL);
body.getDataMap().set("appVersion", APP_VERSION);
body.getDataMap().set("osVersion", browser.version);
body.getDataMap().set("packageName", APP_PACKAGE);
body.getDataMap().set("deviceId", deviceId);
body.getDataMap().set("deviceName", browser.name);
body.getDataMap().set("language", browser.appLanguage);
//绑定cid
//#ifdef APP-PLUS
let clientid=uni.getStorageSync("clientId")
body.getDataMap().set("clientId", clientid);
// #endif
let data = body.serializeBinary();
// console.log(body)
let protobuf = new Uint8Array(data.length + 1);
protobuf[0] = SENT_BODY;
protobuf.set(data, 1);
const buffer = protobuf
this.SocketTask.send({
data: buffer,
success: (res) => {
// console.log(res)
console.log('成功')
},
});
} // '绑定账号' APP_CHANNEL
} uni.setStorageSync('account', String(account))
async sendBufferTag() { let deviceId = uni.getStorageSync('deviceId')
if (this._connectioned) { if (deviceId == "" || deviceId == undefined) {
const tag = this.globalData.tag deviceId = this.generateUUID();
let body = new proto.com.farsunset.cim.sdk.web.model.SentBody(); uni.setStorageSync('deviceId', deviceId)
if(tag){ }
body.setKey("client_set_tag"); let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
body.getDataMap().set("tag", tag); body.setKey("client_bind");
} body.setTimestamp(new Date().getTime());
else body.setKey("client_remove_tag"); body.getDataMap().set("uid", String(account));
let data = body.serializeBinary(); body.getDataMap().set("channel", APP_CHANNEL);
let protobuf = new Uint8Array(data.length + 1); body.getDataMap().set("appVersion", APP_VERSION);
protobuf[0] = SENT_BODY; body.getDataMap().set("osVersion", browser.version);
protobuf.set(data, 1); body.getDataMap().set("packageName", APP_PACKAGE);
const buffer = protobuf body.getDataMap().set("deviceId", deviceId);
this.SocketTask.send({ body.getDataMap().set("deviceName", browser.name);
data: buffer, body.getDataMap().set("language", browser.appLanguage);
success: (res) => { //绑定cid
console.log('成功') //#ifdef APP-PLUS
}, let clientid = uni.getStorageSync("clientId")
}); body.getDataMap().set("clientId", clientid);
} // #endif
} this.sendRequest(body)
generateUUID() { }
let d = new Date().getTime();
let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid.replace(/-/g, '');
}
/**
* 发生错误
* @param {Object} callback
*/
async error(err) {
this.isError = true;
if (this.on_register["error"] !== undefined) {
this.invokeHandlerFunctionOnRegistr("error", err);
}
}
/** }
* 重新连接错误 //绑定tag
* @param {Object} err 错误信息 async sendBufferTag(tag) {
*/ if (this._connectioned) {
async reconnectionError(err) { let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
this.isError = true; if (tag) {
if (this.on_register["reconnectionerror"] !== undefined) { body.setKey("client_set_tag");
this.invokeHandlerFunctionOnRegistr("reconnectionerror", err); body.getDataMap().set("tag", tag);
} } else body.setKey("client_remove_tag");
} this.sendRequest(body)
}
}
// 发送缓存池数据
async sendRequest(body) {
let data = body.serializeBinary();
let protobuf = new Uint8Array(data.length + 1);
protobuf[0] = SENT_BODY;
protobuf.set(data, 1);
const buffer = protobuf
this.SocketTask.send({
data: buffer,
success: (res) => {
console.log('成功')
},
});
}
generateUUID() {
let d = new Date().getTime();
let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid.replace(/-/g, '');
}
/**
* 发生错误
* @param {Object} callback
*/
async error(err) {
this.isError = true;
if (this.on_register["error"] !== undefined) {
this.invokeHandlerFunctionOnRegistr("error", err);
}
}
/** /**
* 连接成功 * 重新连接错误
*/ * @param {Object} err 错误信息
async connectioned() { */
this.isError = false; async reconnectionError(err) {
// 关闭重连状态 this.isError = true;
this.begin_reconnection = false; if (this.on_register["reconnectionerror"] !== undefined) {
this._connectioned = true; this.invokeHandlerFunctionOnRegistr("reconnectionerror", err);
if (this.on_register["connectioned"] !== undefined) { }
this.invokeHandlerFunctionOnRegistr("connectioned"); }
}
this.sendBufferRegister();
this.sendBufferTag()
}
/** /**
* 开始发送心跳 * 连接成功
*/ */
async beginSendHeartBeat() { async connectioned() {
this._heart_rate_interval = setInterval((res) => { this.isError = false;
this.emit(this._heart_rate_type); // 关闭重连状态
this.emitMessageToTargetEventByName("HEARTBEAT", { this.begin_reconnection = false;
msg: "Send a heartbeat to the server...", this._connectioned = true;
}); if (this.on_register["connectioned"] !== undefined) {
}, this._heart_rate); this.invokeHandlerFunctionOnRegistr("connectioned");
} }
}
/** /**
* 将心跳结束 * 开始发送心跳
*/ */
async killApp() { async beginSendHeartBeat() {
this._heart_rate_interval && clearInterval(this._heart_rate_interval); this._heart_rate_interval = setInterval((res) => {
} this.emit(this._heart_rate_type);
this.emitMessageToTargetEventByName("HEARTBEAT", {
msg: "Send a heartbeat to the server...",
});
}, this._heart_rate);
}
/** /**
* 重连socket * 将心跳结束
*/ */
async reconnection() { async killApp() {
// 处于与服务器断开状态并且不是被动断开 this._heart_rate_interval && clearInterval(this._heart_rate_interval);
this._connectioned = false; }
if (!this.closed) {
this.reconnection_time = setTimeout(() => {
this.begin_reconnection = true;
this.connection();
}, 1000);
}
}
/** /**
* 初始化程序 * 重连socket
*/ */
async init() { async reconnection() {
console.log('开始链接init'); // 处于与服务器断开状态并且不是被动断开
this.connection(); this._connectioned = false;
} if (!this.closed) {
this.reconnection_time = setTimeout(() => {
this.begin_reconnection = true;
this.connection();
}, 1000);
}
}
/** /**
* 连接socket * 初始化程序
*/ */
async connection() { async init() {
// 是否有重连任务 console.log('开始链接init');
if (this.reconnection_time) { this.connection();
console.log('clearTimeout') }
clearTimeout(this.reconnection_time);
}
/// 创建一个socket对象,返回socket连接
const SocketTask = uni.connectSocket({
url: this._url,
success: () => {
console.log('connectSocket-success')
},
});
/// 打开连接的监听
SocketTask.onOpen(() => {
this.SocketTask = SocketTask;
console.log('打开中')
// 标记已成功连接socket
this._connectioned = true;
SocketTask.onClose(() => {
// 重新连接
if (!this.closed) {
this.reconnection();
}
});
this.connectioned();
});
SocketTask.onMessage((msg) => { /**
// console.log(msg) * 连接socket
const message = this.changeMsg(msg) */
if (message === false) return async connection() {
try { // 是否有重连任务
this.emitToClientAllEvent(message); if (this.reconnection_time) {
} catch (e) { console.log('clearTimeout')
/// 服务器发来的不是一个标准的数据 clearTimeout(this.reconnection_time);
this.emitToClientNotNameEvents(message); }
} /// 创建一个socket对象,返回socket连接
}); const SocketTask = uni.connectSocket({
url: this._url,
success: () => {
console.log('connectSocket-success')
},
});
/// 打开连接的监听
SocketTask.onOpen(() => {
this.SocketTask = SocketTask;
console.log('打开中')
// 标记已成功连接socket
this._connectioned = true;
SocketTask.onClose(() => {
// 重新连接
if (!this.closed) {
this.reconnection();
}
});
this.connectioned();
});
/// 连接打开失败 SocketTask.onMessage((msg) => {
SocketTask.onError((res) => { // console.log(msg)
// 不在重连状态 const message = this.changeMsg(msg)
if (!this.begin_reconnection) { if (message === false) return
this.error(res); try {
} else { this.emitToClientAllEvent(message);
this.reconnectionError(res); } catch (e) {
} /// 服务器发来的不是一个标准的数据
// 重新连接 this.emitToClientNotNameEvents(message);
this.reconnection(); }
}); });
}
changeMsg(e) { // 格式化消息
let data = new Uint8Array(e.data);
let type = data[0];
let body = data.subarray(DATA_HEADER_LENGTH, data.length);
if (type === PING) {
let pong = new Uint8Array(PONG_BODY.byteLength + 1);
pong[0] = PONG;
pong.set(PONG_BODY, 1);
// console.log('心跳')
this.SocketTask.send({
data: pong,
fail: (e) => {
throw new UniSocketError("Failed to send message to server... " + e);
},
});
return false;
}
if (type == MESSAGE) {
let message = proto.com.farsunset.cim.sdk.web.model.Message.deserializeBinary(body);
// console.log(message)
return message.toObject(false)
}
if (type == REPLY_BODY) { /// 连接打开失败
let message = proto.com.farsunset.cim.sdk.web.model.ReplyBody.deserializeBinary(body); SocketTask.onError((res) => {
// console.log(message) // 不在重连状态
/** if (!this.begin_reconnection) {
* 将proto对象转换成json对象去除无用信息 this.error(res);
*/ } else {
let reply = {}; this.reconnectionError(res);
reply.code = message.getCode(); }
reply.key = message.getKey(); // 重新连接
reply.message = message.getMessage(); this.reconnection();
reply.timestamp = message.getTimestamp(); });
reply.data = {}; }
changeMsg(e) { // 格式化消息
let data = new Uint8Array(e.data);
let type = data[0];
let body = data.subarray(DATA_HEADER_LENGTH, data.length);
if (type === PING) {
let pong = new Uint8Array(PONG_BODY.byteLength + 1);
pong[0] = PONG;
pong.set(PONG_BODY, 1);
// console.log('心跳')
this.SocketTask.send({
data: pong,
fail: (e) => {
throw new UniSocketError("Failed to send message to server... " + e);
},
});
return false;
}
if (type == MESSAGE) {
let message = proto.com.farsunset.cim.sdk.web.model.Message.deserializeBinary(body);
// console.log(message)
return message.toObject(false)
}
/** if (type == REPLY_BODY) {
* 注意遍历map这里的参数 value在前key在后 let message = proto.com.farsunset.cim.sdk.web.model.ReplyBody.deserializeBinary(body);
*/ // console.log(message)
message.getDataMap().forEach(function(v, k) { /**
reply.data[k] = v; * 将proto对象转换成json对象去除无用信息
}); */
return reply let reply = {};
} reply.code = message.getCode();
} reply.key = message.getKey();
/** reply.message = message.getMessage();
* 注销监听 reply.timestamp = message.getTimestamp();
*/ reply.data = {};
off(event, handler) {
const handlers = JSON.stringify(JSON.parse(this.on_register));
for (let i = 0; i < handlers.length; i++) {
if (handler === handlers[i]) {
handlers.splice(i, 1);
}
}
return this.off;
}
// async function handler /**
* 注意遍历map这里的参数 value在前key在后
*/
message.getDataMap().forEach(function(v, k) {
reply.data[k] = v;
});
return reply
}
}
/**
* 注销监听
*/
off(event, handler) {
const handlers = JSON.stringify(JSON.parse(this.on_register));
for (let i = 0; i < handlers.length; i++) {
if (handler === handlers[i]) {
handlers.splice(i, 1);
}
}
return this.off;
}
/** // async function handler
* 给指定的事件发送消息
* @param {Object} name 事件名称
*/
async emitMessageToTargetEventByName(name, data) {
this.invokeHandlerFunctionOnRegistr(name, data);
}
/** /**
* 联系使用on(**)注册的事件 * 给指定的事件发送消息
*/ * @param {Object} name 事件名称
async emitToClientNotNameEvents(msg) { */
this.invokeHandlerFunctionOnRegistr("**", msg); async emitMessageToTargetEventByName(name, data) {
} this.invokeHandlerFunctionOnRegistr(name, data);
}
/** /**
* 联系使用on(*)注册的事件 * 联系使用on(**)注册的事件
*/ */
async emitToClientAllEvent(data) { async emitToClientNotNameEvents(msg) {
this.invokeHandlerFunctionOnRegistr("*", data); this.invokeHandlerFunctionOnRegistr("**", msg);
} }
/** /**
* 获取对象类型 * 联系使用on(*)注册的事件
* @param {Object} o 需要验证的对象 */
*/ async emitToClientAllEvent(data) {
async getType(o) { this.invokeHandlerFunctionOnRegistr("*", data);
return Object.prototype.toString.call(o); }
}
/** /**
* 给指定的事件发送数据 * 获取对象类型
* @param {Object} register 事件 * @param {Object} o 需要验证的对象
* @param {Object} data 需要发送的数据 */
*/ async getType(o) {
async invokeHandlerFunctionOnRegistr(register, data) { return Object.prototype.toString.call(o);
// console.log(data) }
if (this.on_register[register] !== undefined) {
const eventList = this.on_register[register]; /**
for (var i = 0; i < eventList.length; i++) { * 给指定的事件发送数据
const event = eventList[i]; * @param {Object} register 事件
event(data); * @param {Object} data 需要发送的数据
} */
} async invokeHandlerFunctionOnRegistr(register, data) {
} // console.log(data)
if (this.on_register[register] !== undefined) {
const eventList = this.on_register[register];
for (var i = 0; i < eventList.length; i++) {
const event = eventList[i];
event(data);
}
}
}
} }
// 自定义Error // 自定义Error
var __extends = (this && this.__extends) || (function() { var __extends = (this && this.__extends) || (function() {
var extendStatics = function(d, b) { var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || extendStatics = Object.setPrototypeOf ||
({ ({
__proto__: [] __proto__: []
} }
instanceof Array && function(d, b) { instanceof Array && function(d, b) {
d.__proto__ = b; d.__proto__ = b;
}) || }) ||
function(d, b) { function(d, b) {
for (var p in b) for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
}; };
return extendStatics(d, b); return extendStatics(d, b);
}; };
return function(d, b) { return function(d, b) {
if (typeof b !== "function" && b !== null) if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b); extendStatics(d, b);
function __() { function __() {
this.constructor = d; this.constructor = d;
} }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}; };
})(); })();
var UniSocketError = /** @class */ (function(_super) { var UniSocketError = /** @class */ (function(_super) {
__extends(UniSocketError, _super); __extends(UniSocketError, _super);
function UniSocketError(message) { function UniSocketError(message) {
var _this = _super.call(this, message) || this; var _this = _super.call(this, message) || this;
_this.name = 'UniSocketError'; _this.name = 'UniSocketError';
return _this; return _this;
} }
return UniSocketError; return UniSocketError;
}(Error)); }(Error));