socket.on('data', (chunk) => {
const msg = JSON.parse(chunk);
handle(msg);
});let buffer = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => {
buffer += chunk;
let i;
while ((i = buffer.indexOf('\n')) !== -1) {
handle(JSON.parse(buffer.slice(0, i)));
buffer = buffer.slice(i + 1);
}
});TCP is a byte stream, so one data event may hold part of a message or several; framing with newlines splits them correctly.
A port is a number on a machine. A socket is one endpoint of a connection, combining an IP address, a port and a protocol.
No. Regular web pages can use only higher-level protocols such as HTTP, WebSocket, WebTransport and WebRTC.
TCP delivers a stream of bytes, not messages. The app must add framing, such as a length prefix or a delimiter, to know where a message ends.