* Shared handler for both UDS and TCP sockets.
(socket: Socket)
| 181 | * Shared handler for both UDS and TCP sockets. |
| 182 | */ |
| 183 | private setupSocket(socket: Socket): void { |
| 184 | this.clients.add(socket) |
| 185 | this.emit('connection', socket) |
| 186 | |
| 187 | attachNdjsonFramer<PipeMessage>(socket, msg => { |
| 188 | this.emit('message', msg) |
| 189 | const reply = (replyMsg: PipeMessage) => { |
| 190 | replyMsg.from = replyMsg.from ?? this.name |
| 191 | replyMsg.ts = replyMsg.ts ?? new Date().toISOString() |
| 192 | if (!socket.destroyed) { |
| 193 | socket.write(JSON.stringify(replyMsg) + '\n') |
| 194 | } |
| 195 | } |
| 196 | for (const handler of this.handlers) { |
| 197 | handler(msg, reply) |
| 198 | } |
| 199 | }) |
| 200 | |
| 201 | socket.on('close', () => { |
| 202 | this.clients.delete(socket) |
| 203 | this.emit('disconnect', socket) |
| 204 | }) |
| 205 | |
| 206 | socket.on('error', err => { |
| 207 | this.clients.delete(socket) |
| 208 | logError(err) |
| 209 | }) |
| 210 | } |
| 211 | |
| 212 | /** |
| 213 | * Start listening for incoming connections. |