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 // '绑定账号' APP_CHANNEL
let account = String(store.getters.user.id) uni.setStorageSync('account', String(account))
uni.setStorageSync('account', account) let deviceId = uni.getStorageSync('deviceId')
let deviceId = uni.getStorageSync('deviceId') if (deviceId == "" || deviceId == undefined) {
if (deviceId == "" || deviceId == undefined) { deviceId = this.generateUUID();
deviceId = this.generateUUID(); uni.setStorageSync('deviceId', deviceId)
uni.setStorageSync('deviceId', deviceId) }
} let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
let body = new proto.com.farsunset.cim.sdk.web.model.SentBody(); body.setKey("client_bind");
body.setKey("client_bind"); body.setTimestamp(new Date().getTime());
body.setTimestamp(new Date().getTime()); body.getDataMap().set("uid", String(account));
body.getDataMap().set("uid", account); body.getDataMap().set("channel", APP_CHANNEL);
body.getDataMap().set("channel", APP_CHANNEL); body.getDataMap().set("appVersion", APP_VERSION);
body.getDataMap().set("appVersion", APP_VERSION); body.getDataMap().set("osVersion", browser.version);
body.getDataMap().set("osVersion", browser.version); body.getDataMap().set("packageName", APP_PACKAGE);
body.getDataMap().set("packageName", APP_PACKAGE); body.getDataMap().set("deviceId", deviceId);
body.getDataMap().set("deviceId", deviceId); body.getDataMap().set("deviceName", browser.name);
body.getDataMap().set("deviceName", browser.name); body.getDataMap().set("language", browser.appLanguage);
body.getDataMap().set("language", browser.appLanguage); //绑定cid
//绑定cid //#ifdef APP-PLUS
//#ifdef APP-PLUS let clientid = uni.getStorageSync("clientId")
let clientid=uni.getStorageSync("clientId") body.getDataMap().set("clientId", clientid);
body.getDataMap().set("clientId", clientid); // #endif
// #endif this.sendRequest(body)
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('成功')
},
});
} }
} //绑定tag
async sendBufferTag() { async sendBufferTag(tag) {
if (this._connectioned) { if (this._connectioned) {
const tag = this.globalData.tag let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
let body = new proto.com.farsunset.cim.sdk.web.model.SentBody(); if (tag) {
if(tag){ body.setKey("client_set_tag");
body.setKey("client_set_tag"); body.getDataMap().set("tag", tag);
body.getDataMap().set("tag", tag); } else body.setKey("client_remove_tag");
} this.sendRequest(body)
else body.setKey("client_remove_tag"); }
let data = body.serializeBinary(); }
let protobuf = new Uint8Array(data.length + 1); // 发送缓存池数据
protobuf[0] = SENT_BODY; async sendRequest(body) {
protobuf.set(data, 1); let data = body.serializeBinary();
const buffer = protobuf let protobuf = new Uint8Array(data.length + 1);
this.SocketTask.send({ protobuf[0] = SENT_BODY;
data: buffer, protobuf.set(data, 1);
success: (res) => { const buffer = protobuf
console.log('成功') 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) { generateUUID() {
let r = (d + Math.random() * 16) % 16 | 0; let d = new Date().getTime();
d = Math.floor(d / 16); let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); let r = (d + Math.random() * 16) % 16 | 0;
}); d = Math.floor(d / 16);
return uuid.replace(/-/g, ''); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
} });
/** return uuid.replace(/-/g, '');
* 发生错误 }
* @param {Object} callback /**
*/ * 发生错误
async error(err) { * @param {Object} callback
this.isError = true; */
if (this.on_register["error"] !== undefined) { async error(err) {
this.invokeHandlerFunctionOnRegistr("error", err); this.isError = true;
} if (this.on_register["error"] !== undefined) {
} this.invokeHandlerFunctionOnRegistr("error", err);
}
}
/** /**
* 重新连接错误 * 重新连接错误
* @param {Object} err 错误信息 * @param {Object} err 错误信息
*/ */
async reconnectionError(err) { async reconnectionError(err) {
this.isError = true; this.isError = true;
if (this.on_register["reconnectionerror"] !== undefined) { if (this.on_register["reconnectionerror"] !== undefined) {
this.invokeHandlerFunctionOnRegistr("reconnectionerror", err); this.invokeHandlerFunctionOnRegistr("reconnectionerror", err);
} }
} }
/** /**
* 连接成功 * 连接成功
*/ */
async connectioned() { async connectioned() {
this.isError = false; this.isError = false;
// 关闭重连状态 // 关闭重连状态
this.begin_reconnection = false; this.begin_reconnection = false;
this._connectioned = true; this._connectioned = true;
if (this.on_register["connectioned"] !== undefined) { if (this.on_register["connectioned"] !== undefined) {
this.invokeHandlerFunctionOnRegistr("connectioned"); this.invokeHandlerFunctionOnRegistr("connectioned");
} }
}
this.sendBufferRegister(); /**
* 开始发送心跳
*/
async beginSendHeartBeat() {
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);
}
this.sendBufferTag() /**
} * 将心跳结束
*/
async killApp() {
this._heart_rate_interval && clearInterval(this._heart_rate_interval);
}
/** /**
* 开始发送心跳 * 重连socket
*/ */
async beginSendHeartBeat() { async reconnection() {
this._heart_rate_interval = setInterval((res) => { // 处于与服务器断开状态并且不是被动断开
this.emit(this._heart_rate_type); this._connectioned = false;
this.emitMessageToTargetEventByName("HEARTBEAT", { if (!this.closed) {
msg: "Send a heartbeat to the server...", this.reconnection_time = setTimeout(() => {
}); this.begin_reconnection = true;
}, this._heart_rate); this.connection();
} }, 1000);
}
}
/** /**
* 将心跳结束 * 初始化程序
*/ */
async killApp() { async init() {
this._heart_rate_interval && clearInterval(this._heart_rate_interval); console.log('开始链接init');
} this.connection();
}
/** /**
* 重连socket * 连接socket
*/ */
async reconnection() { async connection() {
// 处于与服务器断开状态并且不是被动断开 // 是否有重连任务
this._connectioned = false; if (this.reconnection_time) {
if (!this.closed) { console.log('clearTimeout')
this.reconnection_time = setTimeout(() => { clearTimeout(this.reconnection_time);
this.begin_reconnection = true; }
this.connection(); /// 创建一个socket对象,返回socket连接
}, 1000); 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)
*/ const message = this.changeMsg(msg)
async init() { if (message === false) return
console.log('开始链接init'); try {
this.connection(); this.emitToClientAllEvent(message);
} } catch (e) {
/// 服务器发来的不是一个标准的数据
this.emitToClientNotNameEvents(message);
}
});
/** /// 连接打开失败
* 连接socket SocketTask.onError((res) => {
*/ // 不在重连状态
async connection() { if (!this.begin_reconnection) {
// 是否有重连任务 this.error(res);
if (this.reconnection_time) { } else {
console.log('clearTimeout') this.reconnectionError(res);
clearTimeout(this.reconnection_time); }
} // 重新连接
/// 创建一个socket对象,返回socket连接 this.reconnection();
const SocketTask = uni.connectSocket({ });
url: this._url, }
success: () => { changeMsg(e) { // 格式化消息
console.log('connectSocket-success') let data = new Uint8Array(e.data);
}, let type = data[0];
}); let body = data.subarray(DATA_HEADER_LENGTH, data.length);
/// 打开连接的监听 if (type === PING) {
SocketTask.onOpen(() => { let pong = new Uint8Array(PONG_BODY.byteLength + 1);
this.SocketTask = SocketTask; pong[0] = PONG;
console.log('打开中') pong.set(PONG_BODY, 1);
// 标记已成功连接socket // console.log('心跳')
this._connectioned = true; this.SocketTask.send({
SocketTask.onClose(() => { data: pong,
// 重新连接 fail: (e) => {
if (!this.closed) { throw new UniSocketError("Failed to send message to server... " + e);
this.reconnection(); },
} });
}); return false;
this.connectioned(); }
}); if (type == MESSAGE) {
let message = proto.com.farsunset.cim.sdk.web.model.Message.deserializeBinary(body);
// console.log(message)
return message.toObject(false)
}
SocketTask.onMessage((msg) => { if (type == REPLY_BODY) {
// console.log(msg) let message = proto.com.farsunset.cim.sdk.web.model.ReplyBody.deserializeBinary(body);
const message = this.changeMsg(msg) // console.log(message)
if (message === false) return /**
try { * 将proto对象转换成json对象去除无用信息
this.emitToClientAllEvent(message); */
} catch (e) { let reply = {};
/// 服务器发来的不是一个标准的数据 reply.code = message.getCode();
this.emitToClientNotNameEvents(message); reply.key = message.getKey();
} reply.message = message.getMessage();
}); reply.timestamp = message.getTimestamp();
reply.data = {};
/// 连接打开失败 /**
SocketTask.onError((res) => { * 注意遍历map这里的参数 value在前key在后
// 不在重连状态 */
if (!this.begin_reconnection) { message.getDataMap().forEach(function(v, k) {
this.error(res); reply.data[k] = v;
} else { });
this.reconnectionError(res); return reply
} }
// 重新连接 }
this.reconnection(); /**
}); * 注销监听
} */
changeMsg(e) { // 格式化消息 off(event, handler) {
let data = new Uint8Array(e.data); const handlers = JSON.stringify(JSON.parse(this.on_register));
let type = data[0]; for (let i = 0; i < handlers.length; i++) {
let body = data.subarray(DATA_HEADER_LENGTH, data.length); if (handler === handlers[i]) {
if (type === PING) { handlers.splice(i, 1);
let pong = new Uint8Array(PONG_BODY.byteLength + 1); }
pong[0] = PONG; }
pong.set(PONG_BODY, 1); return this.off;
// 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) { // async function handler
let message = proto.com.farsunset.cim.sdk.web.model.ReplyBody.deserializeBinary(body);
// console.log(message)
/**
* 将proto对象转换成json对象去除无用信息
*/
let reply = {};
reply.code = message.getCode();
reply.key = message.getKey();
reply.message = message.getMessage();
reply.timestamp = message.getTimestamp();
reply.data = {};
/** /**
* 注意遍历map这里的参数 value在前key在后 * 给指定的事件发送消息
*/ * @param {Object} name 事件名称
message.getDataMap().forEach(function(v, k) { */
reply.data[k] = v; async emitMessageToTargetEventByName(name, data) {
}); this.invokeHandlerFunctionOnRegistr(name, data);
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 /**
* 联系使用on(**)注册的事件
*/
async emitToClientNotNameEvents(msg) {
this.invokeHandlerFunctionOnRegistr("**", msg);
}
/** /**
* 给指定的事件发送消息 * 联系使用on(*)注册的事件
* @param {Object} name 事件名称 */
*/ async emitToClientAllEvent(data) {
async emitMessageToTargetEventByName(name, data) { this.invokeHandlerFunctionOnRegistr("*", data);
this.invokeHandlerFunctionOnRegistr(name, data); }
}
/** /**
* 联系使用on(**)注册的事件 * 获取对象类型
*/ * @param {Object} o 需要验证的对象
async emitToClientNotNameEvents(msg) { */
this.invokeHandlerFunctionOnRegistr("**", msg); async getType(o) {
} return Object.prototype.toString.call(o);
}
/** /**
* 联系使用on(*)注册的事件 * 给指定的事件发送数据
*/ * @param {Object} register 事件
async emitToClientAllEvent(data) { * @param {Object} data 需要发送的数据
this.invokeHandlerFunctionOnRegistr("*", data); */
} async invokeHandlerFunctionOnRegistr(register, data) {
// console.log(data)
/** if (this.on_register[register] !== undefined) {
* 获取对象类型 const eventList = this.on_register[register];
* @param {Object} o 需要验证的对象 for (var i = 0; i < eventList.length; i++) {
*/ const event = eventList[i];
async getType(o) { event(data);
return Object.prototype.toString.call(o); }
} }
}
/**
* 给指定的事件发送数据
* @param {Object} register 事件
* @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));