UNPKG

imsdk-server-core

Version:

轻量级Web服务器框架、WebSocket服务器框架。采用Typescript编写,简单易用。

159 lines (158 loc) 3.97 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WssSession = void 0; /** * ws的WebSocket封装类 * ws相关信息:https://github.com/websockets/ws */ const ws_1 = __importDefault(require("ws")); class WssSession { /** * @param socket * @param ip */ constructor(socket, ip) { this._id = WssSession._increment++; this._socket = socket; this._ip = ip; this._uid = null; this._context = {}; this._channel = {}; this._reqIdList = []; this._lastHeart = Date.now(); } /** * 使用WebSocket发送数据 * @param data 要发送的数据 * @param options 具体属性参考依赖库 https://github.com/expressjs/multer * @param cb 发送后的回调 */ send(data, options, cb) { if (this._socket && this._socket.readyState === ws_1.default.OPEN) { this._socket.send(data, options, cb); return true; } else { return false; } } /** * 关闭WebSocket * 本框架保留状态码: * 4001-4100 服务端保留状态码范围 * 4101-4200 客户端保留状态码范围 * 4201-4999 可自定义的状态码范围 * 更多状态码资料参考: https://tools.ietf.org/html/rfc6455#section-7.4.2 和 https://github.com/websockets/ws/issues/715 * @param code * @param reason */ close(code, reason) { if (this._socket) { this._socket.close(code, reason); this._socket = null; } } /** * 绑定用户ID * @param uid */ bindUid(uid) { this._uid = uid; } /** * 解绑用户ID */ unbindUid() { this._uid = null; } /** * 缓存键值对数据 * @param key * @param value */ setContext(key, value) { this._context[key] = value; } /** * 读取键值对数据 * @param key */ getContext(key) { return this._context[key]; } /** * 删除键值对数据 * @param key */ delContext(key) { delete this._context[key]; } /** * 加入指定推送组 * @param gid */ joinChannel(gid) { this._channel[gid.toString()] = true; } /** * 退出指定推送组 * @param gid */ quitChannel(gid) { delete this._channel[gid.toString()]; } /** * 遍历已加入的全部推送组 * @param callback */ eachChannel(callback) { for (let gid in this._channel) { callback(gid); } } /** * 更新流量统计信息,同时返回是否收到重复包 * @param reqId 请求id * @param cacheSize 缓存reqId数量上限 */ updateReqId(reqId, cacheSize) { if (this._reqIdList.lastIndexOf(reqId) >= 0) { return false; //收到重复包 } else { if (this._reqIdList.length >= cacheSize) { this._reqIdList.splice(0, Math.floor(cacheSize / 2)); //清掉队列前的一半缓存 } this._reqIdList.push(reqId); return true; } } /** * 更新最近收到心跳包的时间 */ updateHeart() { this._lastHeart = Date.now(); } /** * 是否绑定了UID */ isBinded() { return !!this._uid; } /** * 是否已经超时未收到心跳包 * @param timeout */ isExpired(timeout) { return Date.now() > this._lastHeart + timeout; } get id() { return this._id; } get ip() { return this._ip; } get uid() { return this._uid; } get ouid() { return this._uid; } } exports.WssSession = WssSession; WssSession._increment = 1;