| 315 | }; |
| 316 | |
| 317 | const dataHandler = function (server, self, connection) { |
| 318 | return function (data) { |
| 319 | // Parse until we are done with the data |
| 320 | while (data.length > 0) { |
| 321 | // Call the onRead function |
| 322 | if (typeof server.onRead === 'function') { |
| 323 | // If onRead returns true, terminate the reading for this connection as |
| 324 | // it's dead |
| 325 | if (server.onRead(server, connection, self.buffer, self.bytesRead)) { |
| 326 | break; |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // If we still have bytes to read on the current message |
| 331 | if (self.bytesRead > 0 && self.sizeOfMessage > 0) { |
| 332 | // Calculate the amount of remaining bytes |
| 333 | let remainingBytesToRead = self.sizeOfMessage - self.bytesRead; |
| 334 | // Check if the current chunk contains the rest of the message |
| 335 | if (remainingBytesToRead > data.length) { |
| 336 | // Copy the new data into the exiting buffer (should have been allocated when we know the message size) |
| 337 | data.copy(self.buffer, self.bytesRead); |
| 338 | // Adjust the number of bytes read so it point to the correct index in the buffer |
| 339 | self.bytesRead = self.bytesRead + data.length; |
| 340 | |
| 341 | // Reset state of buffer |
| 342 | data = Buffer.alloc(0); |
| 343 | } else { |
| 344 | // Copy the missing part of the data into our current buffer |
| 345 | data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); |
| 346 | // Slice the overflow into a new buffer that we will then re-parse |
| 347 | data = data.slice(remainingBytesToRead); |
| 348 | |
| 349 | // Emit current complete message |
| 350 | try { |
| 351 | let emitBuffer = self.buffer; |
| 352 | // Reset state of buffer |
| 353 | self.buffer = null; |
| 354 | self.sizeOfMessage = 0; |
| 355 | self.bytesRead = 0; |
| 356 | self.stubBuffer = null; |
| 357 | // Emit the buffer |
| 358 | server.emit('message', protocol(server, emitBuffer), connection); |
| 359 | } catch (err) { |
| 360 | let errorObject = { |
| 361 | err: 'socketHandler', |
| 362 | trace: err, |
| 363 | bin: self.buffer, |
| 364 | parseState: { |
| 365 | sizeOfMessage: self.sizeOfMessage, |
| 366 | bytesRead: self.bytesRead, |
| 367 | stubBuffer: self.stubBuffer |
| 368 | } |
| 369 | }; |
| 370 | // We got a parse Error fire it off then keep going |
| 371 | server.emit('parseError', errorObject, self); |
| 372 | } |
| 373 | } |
| 374 | } else { |