MCPcopy
hub / github.com/tsrpc/tsrpc / connect

Method connect

src/client/ws/WsClient.ts:32–110  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

30
31 private _connecting?: Promise<void>;
32 async connect(): Promise<void> {
33 // 已连接中
34 if (this._connecting) {
35 return this._connecting;
36 }
37
38 // 已连接成功
39 if (this._ws) {
40 return;
41 }
42
43 let ws = new (WebSocket as any)(this.options.server) as WebSocket;
44 this.logger.log(`Start connecting ${this.options.server}...`)
45 this._connecting = new Promise<void>((rs: Function, rj?: Function) => {
46 ws.onopen = () => {
47 this._connecting = undefined;
48 rs();
49 rj = undefined;
50 ws.onopen = undefined as any;
51 this._ws = ws;
52 this.logger.log('Connected succ');
53 this.options.onStatusChange && this.options.onStatusChange('open');
54 };
55
56 ws.onerror = e => {
57 this.logger.error('[WebSocket Error]', e.message);
58 // 还在连接中,则连接失败
59 if (rj) {
60 this._connecting = undefined;
61 rj(new TsrpcError(e.message, {
62 code: e.error && e.error.code,
63 isNetworkError: true
64 }));
65 }
66 }
67
68 ws.onclose = e => {
69 if (rj) {
70 this._connecting = undefined;
71 rj(new TsrpcError('Network Error', {
72 code: e.reason,
73 isNetworkError: true
74 }));
75 }
76
77 // 清空WebSocket Listener
78 ws.onopen = ws.onclose = ws.onmessage = ws.onerror = undefined as any;
79 this._ws = undefined;
80
81 this.options.onStatusChange && this.options.onStatusChange('closed');
82
83 if (this._rsDisconnecting) {
84 this._rsDisconnecting();
85 this._rsDisconnecting = undefined;
86 this.logger.log('Disconnected succ', `code=${e.code} reason=${e.reason}`);
87 }
88 // 已连接上 非主动关闭 触发掉线
89 else if (rj) {

Callers 3

mainFunction · 0.95
mainFunction · 0.80
ws.test.tsFile · 0.80

Calls 3

_onBufferMethod · 0.95
logMethod · 0.65
errorMethod · 0.65

Tested by

no test coverage detected