-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwsConnector.ts
More file actions
147 lines (126 loc) · 6.01 KB
/
Copy pathwsConnector.ts
File metadata and controls
147 lines (126 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { ICloseEvent, w3cwebsocket } from 'websocket';
import { ErrorCode, TDWebSocketClientError, WebSocketQueryError } from '../common/wsError'
import { OnMessageType, WsEventCallback } from './wsEventCallback';
import logger from '../common/log';
import { ReqId } from '../common/reqid';
export class WebSocketConnector {
private _wsConn: w3cwebsocket;
private _wsURL: URL;
_timeout = 5000;
// create ws
constructor(url: URL, timeout :number | undefined | null) {
// return w3bsocket3
if (url) {
this._wsURL = url;
let origin = url.origin;
let pathname = url.pathname;
let search = url.search;
if (timeout) {
this._timeout = timeout
}
this._wsConn = new w3cwebsocket(origin.concat(pathname).concat(search), undefined, undefined, undefined, undefined, {maxReceivedFrameSize:0x60000000, maxReceivedMessageSize:0x60000000});
this._wsConn.onerror = function (err: Error) { logger.error(`webSocket connection failed, url: ${this.url}, error: ${err.message}`);}
this._wsConn.onclose = this._onclose
this._wsConn.onmessage = this._onmessage
this._wsConn._binaryType = "arraybuffer"
} else {
throw new WebSocketQueryError(ErrorCode.ERR_INVALID_URL, "websocket URL must be defined")
}
}
async ready() {
return new Promise((resolve, reject) => {
let reqId = ReqId.getReqID();
WsEventCallback.instance().registerCallback({ action: "websocket_connection", req_id: BigInt(reqId),
timeout:this._timeout, id: BigInt(reqId)}, resolve, reject);
this._wsConn.onopen = () => {
logger.debug("websocket connection opened")
WsEventCallback.instance().handleEventCallback({id: BigInt(reqId), action:"websocket_connection", req_id:BigInt(reqId)},
OnMessageType.MESSAGE_TYPE_CONNECTION, this);
}
})
}
private async _onclose(e: ICloseEvent) {
logger.info("websocket connection closed")
}
private _onmessage(event: any) {
let data = event.data;
logger.debug("wsClient._onMessage()====" + (Object.prototype.toString.call(data)))
if (Object.prototype.toString.call(data) === '[object ArrayBuffer]') {
let id = new DataView(data, 26, 8).getBigUint64(0, true);
WsEventCallback.instance().handleEventCallback({id:id, action:'', req_id:BigInt(0)},
OnMessageType.MESSAGE_TYPE_ARRAYBUFFER, data);
} else if (Object.prototype.toString.call(data) === '[object String]') {
let msg = JSON.parse(data)
logger.debug("[_onmessage.stringType]==>:" + data);
WsEventCallback.instance().handleEventCallback({id:BigInt(0), action:msg.action, req_id:msg.req_id},
OnMessageType.MESSAGE_TYPE_STRING, msg);
} else {
throw new TDWebSocketClientError(ErrorCode.ERR_INVALID_MESSAGE_TYPE, `invalid message type ${Object.prototype.toString.call(data)}`);
}
}
close() {
if (this._wsConn) {
this._wsConn.close();
} else {
throw new TDWebSocketClientError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL, "WebSocket connection is undefined.")
}
}
readyState(): number {
return this._wsConn.readyState;
}
async sendMsgNoResp(message: string):Promise<void> {
logger.debug("[wsClient.sendMsgNoResp()]===>" + message)
let msg = JSON.parse(message);
if (msg.args.id !== undefined) {
msg.args.id = BigInt(msg.args.id)
}
return new Promise((resolve, reject) => {
if (this._wsConn && this._wsConn.readyState === w3cwebsocket.OPEN) {
this._wsConn.send(message)
resolve()
} else {
reject(new WebSocketQueryError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`WebSocket connection is not ready,status :${this._wsConn?.readyState}`))
}
})
}
async sendMsg(message: string, register: Boolean = true) {
logger.debug("[wsClient.sendMessage()]===>" + message)
let msg = JSON.parse(message);
if (msg.args.id !== undefined) {
msg.args.id = BigInt(msg.args.id)
}
return new Promise((resolve, reject) => {
if (this._wsConn && this._wsConn.readyState === w3cwebsocket.OPEN) {
if (register) {
WsEventCallback.instance().registerCallback({ action: msg.action, req_id: msg.args.req_id,
timeout:this._timeout, id: msg.args.id === undefined ? msg.args.id : BigInt(msg.args.id) },
resolve, reject);
}
logger.debug(`[wsClient.sendMessage.msg]===> ${message}`)
this._wsConn.send(message)
} else {
reject(new WebSocketQueryError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`WebSocket connection is not ready,status :${this._wsConn?.readyState}`))
}
})
}
async sendBinaryMsg(reqId: bigint, action:string, message: ArrayBuffer, register: Boolean = true) {
return new Promise((resolve, reject) => {
if (this._wsConn && this._wsConn.readyState === w3cwebsocket.OPEN) {
if (register) {
WsEventCallback.instance().registerCallback({ action: action, req_id: reqId,
timeout:this._timeout, id: reqId}, resolve, reject);
}
logger.debug("[wsClient.sendBinaryMsg()]===>" + reqId + action + message.byteLength)
this._wsConn.send(message)
} else {
reject(new WebSocketQueryError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`WebSocket connection is not ready,status :${this._wsConn?.readyState}`))
}
})
}
public getWsURL(): URL {
return this._wsURL;
}
}