| 99 | } |
| 100 | |
| 101 | protected _sendBuf(buf: Uint8Array, options: TransportOptions = {}, type: 'api' | 'msg', sn: number): SuperPromise<Buffer | undefined, TsrpcError> { |
| 102 | let httpReq: http.ClientRequest; |
| 103 | |
| 104 | let promiseRj: Function; |
| 105 | let promise = new SuperPromise<Buffer>((rs, rj) => { |
| 106 | promiseRj = rj; |
| 107 | httpReq = this._http.request(this._options.server, { |
| 108 | method: 'POST', |
| 109 | agent: this._options.agent |
| 110 | }, httpRes => { |
| 111 | let data: Buffer[] = []; |
| 112 | httpRes.on('data', (v: Buffer) => { |
| 113 | data.push(v) |
| 114 | }); |
| 115 | httpRes.on('end', () => { |
| 116 | let buf = Buffer.concat(data) |
| 117 | this.lastReceivedBuf = buf; |
| 118 | rs(buf); |
| 119 | }) |
| 120 | }); |
| 121 | |
| 122 | httpReq.on('abort', () => { |
| 123 | if (!promise.isDone) { |
| 124 | this.logger.log(`[${type === 'api' ? 'ApiCancel' : 'MsgCancel'}] #${sn}`) |
| 125 | } |
| 126 | }); |
| 127 | |
| 128 | httpReq.on('error', e => { |
| 129 | // abort 不算错误 |
| 130 | if (promise.isCanceled) { |
| 131 | return; |
| 132 | } |
| 133 | |
| 134 | rj(new TsrpcError(e.message, { |
| 135 | code: (e as any).code, |
| 136 | isNetworkError: true |
| 137 | })); |
| 138 | }) |
| 139 | |
| 140 | httpReq.write(Buffer.from(buf)); |
| 141 | httpReq.end(); |
| 142 | }); |
| 143 | |
| 144 | promise.onCancel(() => { |
| 145 | httpReq.abort(); |
| 146 | }); |
| 147 | |
| 148 | let timer: NodeJS.Timeout | undefined; |
| 149 | let timeout = options.timeout || this._options.timeout; |
| 150 | if (timeout) { |
| 151 | timer = setTimeout(() => { |
| 152 | if (!promise.isCanceled && !promise.isDone) { |
| 153 | this.logger.log(`[${type === 'api' ? 'ApiTimeout' : 'MsgTimeout'}] #${sn}`); |
| 154 | promiseRj(new TsrpcError('Request Timeout', { |
| 155 | code: 'TIMEOUT', |
| 156 | isNetworkError: true |
| 157 | })); |
| 158 | httpReq.abort(); |