Reputation: 943
I have a question about Node.js tcp socket and on('data') event.
For example, my client sends data to socket with the very very long message socket.write('<VERY LONG MESSAGE>')
;
The server is listening port and receiving that data.
Could the <VERY LONG MESSAGE>
be received with server data
event not from its start byte? (For example to be chunked by 3 or more parts).
I know about coalescing messages but what about chunking?
Should I implement the received data size validation and coalesce result of few data
events results for my socket or socket.write
usually sends messages without chunking?
Upvotes: 2
Views: 2531
Reputation: 141
Yes, chunking on both write
and when receiving a payload internally can happen.
Sockets are managed by the operating system kernel. Since network I/O can take time they typically use two queue buffers for sockets; one for sending and one for receiving data. Because of that chunked message sizes may vary with different platforms.
Test for yourself:
const net = require("net");
var server = net.createServer({
allowHalfOpen: false,
pauseOnConnect: false
}, function(serversideSocket) {
console.log("socket connected");
serversideSocket.on("data", function(data) {
console.log(`got data of size ${data.length}`);
});
serversideSocket.on("end", function() {
console.log("client disconnected, closing");
server.close();
});
}).listen(1337, "127.0.0.1", function() {
console.log("server listening");
var clientsideSocket = net.createConnection({
port: 1337,
host: "127.0.0.1",
allowHalfOpen: false
});
var sendBuffer = Buffer.allocUnsafe(1048576);
clientsideSocket.write(sendBuffer);
clientsideSocket.end();
});
Here's my output:
server listening
socket connected
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
got data of size 65536
client disconnected, closing
Upvotes: 2