Node's net module, for data reading and writing problems

using node"s net module
, the format of transmission is expected to be json, but net.write only supports buffer and strings
, so I use json.stringify to format object data

when running a chat room, the first user logs in and prints normally, while the second user reports an error because of the data method of monitoring, and the data sent back is continuous

.

as shown in the figure: abbreviated writing

server

var json = JSON.stringify
socket.write(json ("1"))
socket.write(json ("2"))
socket.write(json ("3"))

client

socket.on("data", function (data) {
    data = JSON.parse(data);
    console.log(data )
  });

clipboard.png

clipboard.png

where message and userList call socket.write, successively, such as:

socket.write ({type: "message",.})
socket.write ({type:" userList",.})

how to implement a write, client to print once, instead of accepting it all and then triggering the function to print.
and why it can be printed successfully the first time.

Dec.10,2021

when streaming, the data is continuous. If you need logical separation, you can send a separator yourself after sending a piece of logical data, and then segment it with a delimiter on the client.


the TCP protocol of the default node.js enables the nagle algorithm, which suspends the sending of small packets and automatically splices small packets into large packets to save money. What you are doing now relies on the assumption that each write sends a packet and triggers a data event on the other side, but there is no guarantee that sometimes your data will be sent to the other end several times. You have to define the format of the application layer packet, or the end flag of the packet, and use an end flag to explicitly separate multiple pieces of data. For example, you can use \ n , which will never appear in your data, as the closing flag, and then when dealing with data events, cache the previous data each time until you read \ n and then intercept the corresponding part of the processing.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf78f9-315cf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf78f9-315cf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?