| 158 | } |
| 159 | |
| 160 | export class SocketMessageWriter extends AbstractMessageWriter implements MessageWriter { |
| 161 | |
| 162 | private socket: Socket; |
| 163 | private queue: Message[]; |
| 164 | private sending: boolean; |
| 165 | private encoding: string; |
| 166 | private errorCount: number; |
| 167 | |
| 168 | public constructor(socket: Socket, encoding: string = 'utf8') { |
| 169 | super(); |
| 170 | this.socket = socket; |
| 171 | this.queue = []; |
| 172 | this.sending = false; |
| 173 | this.encoding = encoding; |
| 174 | this.errorCount = 0; |
| 175 | this.socket.on('error', (error: any) => this.fireError(error)); |
| 176 | this.socket.on('close', () => this.fireClose()); |
| 177 | } |
| 178 | |
| 179 | public write(msg: Message): void { |
| 180 | if (!this.sending && this.queue.length === 0) { |
| 181 | // See https://github.com/nodejs/node/issues/7657 |
| 182 | this.doWriteMessage(msg); |
| 183 | } else { |
| 184 | this.queue.push(msg); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | public doWriteMessage(msg: Message): void { |
| 189 | let json = JSON.stringify(msg); |
| 190 | let contentLength = Buffer.byteLength(json, this.encoding); |
| 191 | |
| 192 | let headers: string[] = [ |
| 193 | ContentLength, contentLength.toString(), CRLF, |
| 194 | CRLF |
| 195 | ]; |
| 196 | try { |
| 197 | // Header must be written in ASCII encoding |
| 198 | this.sending = true; |
| 199 | this.socket.write(headers.join(''), 'ascii', (error: any) => { |
| 200 | if (error) { |
| 201 | this.handleError(error, msg); |
| 202 | } |
| 203 | try { |
| 204 | // Now write the content. This can be written in any encoding |
| 205 | this.socket.write(json, this.encoding, (error: any) => { |
| 206 | this.sending = false; |
| 207 | if (error) { |
| 208 | this.handleError(error, msg); |
| 209 | } else { |
| 210 | this.errorCount = 0; |
| 211 | } |
| 212 | if (this.queue.length > 0) { |
| 213 | this.doWriteMessage(this.queue.shift()!); |
| 214 | } |
| 215 | }); |
| 216 | } catch (error) { |
| 217 | this.handleError(error, msg); |
nothing calls this directly
no outgoing calls
no test coverage detected