0

I'm trying to send some information from my server to my client with TCP and it's formatted in JSON. I'm using the net module. When my socket object emits the "on data" event, I want to convert the bytestream to text and parse it with json. The problem is that the data sometimes contain data from two separate TCP packages. This happens when the server sends data very quickly.

Since I then have two JSON strings in the data string, I cannot use the parse. I could use string manipulation, but that seems like a bad solution. I know that it's two separate TCP packages, confirmed by wireshark. How can I deal with this?

"use strict";
let net = require('net');
let client = new net.Socket();

var port = 8172;
var host = 'localhost';


client.connect({port: port, host:host}, () =>{
   console.log("Connected");
});

client.on('data',(data)=>{
    console.log(data.toString()); //I want to use JSON.parse() here
});
Slason
  • 3
  • 4

1 Answers1

0

The problem is that the stream infrastructure is dealing with data and it doesn't emit the event for every network packet. I suggest you to pipe the socket stream into a transformation that separate messages using special markers (maybe you can add a new line character at the end of every message). Or you can go using contributed packages for json stream processing. This and this could give you some ideas.

Community
  • 1
  • 1
yeiniel
  • 2,416
  • 15
  • 31