Skip to content

Commit

Permalink
perf: 针对内存泄漏的格式化、调整细节
Browse files Browse the repository at this point in the history
  • Loading branch information
ostli committed Jan 27, 2022
1 parent 1203f94 commit 79a03c1
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 44 deletions.
4 changes: 2 additions & 2 deletions src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GetWsParam, SessionEvents, SessionRecord, WebsocketCloseReason } from '
import Session from '@src/client/session/session';
import { EventEmitter } from 'ws';

const MAX_RETRY = 5;
const MAX_RETRY = 10;

export default class WebsocketClient extends EventEmitter {
session!: Session;
Expand All @@ -15,7 +15,7 @@ export default class WebsocketClient extends EventEmitter {
this.on(SessionEvents.EVENT_WS, (data) => {
switch (data.eventType) {
case SessionEvents.RECONNECT:
console.log('[CLIENT] 等待断线重连中。。。');
console.log('[CLIENT] 等待断线重连中...');
break;
case SessionEvents.DISCONNECT:
if (this.retry < (config.maxRetry || MAX_RETRY)) {
Expand Down
38 changes: 21 additions & 17 deletions src/client/session/session.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {GetWsParam, SessionEvents, SessionRecord, WsObjRequestOptions} from '@src/types/websocket-types';
import {Ws} from '@src/client/websocket/websocket';
import {EventEmitter} from 'ws';
import { GetWsParam, SessionEvents, SessionRecord, WsObjRequestOptions } from '@src/types/websocket-types';
import { Ws } from '@src/client/websocket/websocket';
import { EventEmitter } from 'ws';
import resty from 'resty-client';
import {addAuthorization} from "@src/utils/utils";
import { addAuthorization } from '@src/utils/utils';

export default class Session {
config: GetWsParam;
Expand All @@ -18,28 +18,32 @@ export default class Session {
if (sessionRecord) {
this.sessionRecord = sessionRecord;
}
this.createSession()
this.createSession();
}

// 新建会话
createSession() {
this.ws = new Ws(this.config, this.event, this.sessionRecord || undefined);
// 拿到 ws地址等信息
const reqOptions = WsObjRequestOptions(this.config.sandbox)
addAuthorization(reqOptions.headers, this.config.appID, this.config.token)
resty.create(reqOptions)
const reqOptions = WsObjRequestOptions(this.config.sandbox as boolean);

addAuthorization(reqOptions.headers, this.config.appID, this.config.token);

resty
.create(reqOptions)
.get(reqOptions.url as string, {})
.then(r => {
const wsData = r.data
if (!wsData) throw new Error("获取ws连接信息异常")
.then((r) => {
const wsData = r.data;
if (!wsData) throw new Error('获取ws连接信息异常');
this.ws.createWebsocket(wsData);
}).catch(e => {
console.log('[ERROR] createSession: ', e)
this.event.emit(SessionEvents.EVENT_WS, {
eventType: SessionEvents.DISCONNECT,
eventMsg: this.sessionRecord
})
})
.catch((e) => {
console.log('[ERROR] createSession: ', e);
this.event.emit(SessionEvents.EVENT_WS, {
eventType: SessionEvents.DISCONNECT,
eventMsg: this.sessionRecord,
});
});
}

// 关闭会话
Expand Down
35 changes: 17 additions & 18 deletions src/client/websocket/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import {
WsEventType,
wsResData,
} from '@src/types/websocket-types';
import WebSocket, {EventEmitter} from 'ws';
import {toObject} from '@src/utils/utils';
import {Properties} from '@src/utils/constants';
import WebSocket, { EventEmitter } from 'ws';
import { toObject } from '@src/utils/utils';
import { Properties } from '@src/utils/constants';

// websocket连接
export class Ws {
Expand Down Expand Up @@ -56,7 +56,6 @@ export class Ws {

// 创建监听
createListening() {

// websocket连接已开启
this.ws.on('open', () => {
console.log(`[CLIENT] 开启`);
Expand All @@ -80,15 +79,15 @@ export class Ws {
// 鉴权通过
if (wsRes.t === SessionEvents.READY) {
console.log(`[CLIENT] 鉴权通过`);
const {d, s} = wsRes;
const {session_id} = d;
const { d, s } = wsRes;
const { session_id } = d;
// 获取当前会话参数
if (session_id && s) {
this.sessionRecord.sessionID = session_id;
this.sessionRecord.seq = s;
this.heartbeatParam.d = s;
}
this.event.emit(SessionEvents.READY, {eventType: SessionEvents.READY, msg: d || ''});
this.event.emit(SessionEvents.READY, { eventType: SessionEvents.READY, msg: d || '' });
// 第一次发送心跳
console.log(`[CLIENT] 发送第一次心跳`, this.heartbeatParam);
this.sendWs(this.heartbeatParam);
Expand All @@ -98,8 +97,8 @@ export class Ws {
// 心跳测试
if (wsRes.op === OpCode.HEARTBEAT_ACK || wsRes.t === SessionEvents.RESUMED) {
if (!this.alive) {
this.alive = true
this.event.emit(SessionEvents.EVENT_WS, {eventType: SessionEvents.READY});
this.alive = true;
this.event.emit(SessionEvents.EVENT_WS, { eventType: SessionEvents.READY });
}
console.log('[CLIENT] 心跳校验', this.heartbeatParam);
setTimeout(() => {
Expand All @@ -110,13 +109,13 @@ export class Ws {
// 收到服务端锻炼重连的通知
if (wsRes.op === OpCode.RECONNECT) {
// 通知会话,当前已断线
this.event.emit(SessionEvents.EVENT_WS, {eventType: SessionEvents.RECONNECT});
this.event.emit(SessionEvents.EVENT_WS, { eventType: SessionEvents.RECONNECT });
}

// 服务端主动推送的消息
if (wsRes.op === OpCode.DISPATCH) {
// 更新心跳唯一值
const {s} = wsRes;
const { s } = wsRes;
if (s) {
this.sessionRecord.seq = s;
this.heartbeatParam.d = s;
Expand All @@ -130,11 +129,11 @@ export class Ws {
this.ws.on('close', (data: number) => {
console.log('[CLIENT] 连接关闭', data);
// 通知会话,当前已断线
this.alive = false
this.alive = false;
this.event.emit(SessionEvents.EVENT_WS, {
eventType: SessionEvents.DISCONNECT,
eventMsg: this.sessionRecord,
code: data
code: data,
});
if (data) {
this.handleWsCloseEvent(data);
Expand All @@ -144,10 +143,10 @@ export class Ws {
// 监听websocket错误
this.ws.on('error', () => {
console.log(`[CLIENT] 连接错误`);
this.event.emit(SessionEvents.CLOSED, {eventType: SessionEvents.CLOSED});
this.event.emit(SessionEvents.CLOSED, { eventType: SessionEvents.CLOSED });
});

return this.ws
return this.ws;
}

// 连接ws
Expand Down Expand Up @@ -181,7 +180,7 @@ export class Ws {
// 判断用户有没有给到需要监听的事件类型
const intentsIn = this.getValidIntentsType();
if (intentsIn.length > 0) {
const intents = {value: 0};
const intents = { value: 0 };
if (intentsIn.length === 1) {
intents.value = IntentEvents[intentsIn[0]];
return intents.value;
Expand Down Expand Up @@ -267,7 +266,7 @@ export class Ws {
const msg = wsRes.d;
// 如果没有事件,即刻退出
if (!msg || !eventType) return;
this.event.emit(WsEventType[eventType], {eventType, msg});
this.event.emit(WsEventType[eventType], { eventType, msg });
}

// 主动关闭会话
Expand All @@ -279,7 +278,7 @@ export class Ws {
handleWsCloseEvent(code: number) {
WebsocketCloseReason.forEach((e) => {
if (e.code === code) {
this.event.emit(SessionEvents.ERROR, {eventType: SessionEvents.ERROR, msg: e.reason});
this.event.emit(SessionEvents.ERROR, { eventType: SessionEvents.ERROR, msg: e.reason });
}
});
}
Expand Down
14 changes: 7 additions & 7 deletions src/types/websocket-types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {apiVersion} from '@src/openapi/v1/openapi';
import {getURL} from '@src/openapi/v1/resource';
import {buildUrl} from "@src/utils/utils";
import { apiVersion } from '@src/openapi/v1/openapi';
import { getURL } from '@src/openapi/v1/resource';
import { buildUrl } from '@src/utils/utils';

// websocket建立成功回包
export interface wsResData {
Expand Down Expand Up @@ -29,7 +29,7 @@ export interface EventTypes {
export interface GetWsParam {
appID: string;
token: string;
sandbox: boolean;
sandbox?: boolean;
shards?: Array<number>;
intents?: Array<AvailableIntentsEventsEnum>;
maxRetry?: number;
Expand Down Expand Up @@ -171,12 +171,12 @@ export const WebsocketCloseReason = [
{
code: 4008,
reason: '发送 payload 过快,请重新连接,并遵守连接后返回的频控信息',
resume: true
resume: true,
},
{
code: 4009,
reason: '连接过期,请重连',
resume: true
resume: true,
},
{
code: 4010,
Expand Down Expand Up @@ -258,7 +258,7 @@ export const SessionEvents = {
DISCONNECT: 'DISCONNECT', // 断线
EVENT_WS: 'EVENT_WS', // 内部通信
RESUMED: 'RESUMED', // 重连
DEAD: 'DEAD'// 连接已死亡,请检查网络或重启
DEAD: 'DEAD', // 连接已死亡,请检查网络或重启
};

// ws地址配置
Expand Down

0 comments on commit 79a03c1

Please sign in to comment.