Skip to content

Instantly share code, notes, and snippets.

@Den2016
Created February 27, 2020 08:57
Show Gist options
  • Save Den2016/d88af43dd66ee27dfa932c71ed73efef to your computer and use it in GitHub Desktop.
Save Den2016/d88af43dd66ee27dfa932c71ed73efef to your computer and use it in GitHub Desktop.
how send string with his length in first 4 bytes via socket in node.js
// Include Nodejs' net module.
const Net = require('net');
// The port number and hostname of the server.
const port = 55555;
const host = 'localhost';
// Create a new TCP client.
const client = new Net.Socket();
// Send a connection request to the server.
client.connect({ port: port, host: host }, function() {
// If there is no error, the server has accepted the request and created a new
// socket dedicated to us.
console.log('TCP connection established with the server.');
var buffer = Buffer.from('Hello from node.js socket\n', "binary");
//create a buffer with +4 bytes
var consolidatedBuffer = Buffer.alloc(4 + buffer.length);
//write at the beginning of the buffer, the total size using Little Endian
consolidatedBuffer.writeInt32LE(buffer.length, 0);
//Copy the message buffer to the consolidated buffer at position 4 (after the 4 bytes about the size)
buffer.copy(consolidatedBuffer, 4);
// The client can now send data to the server by writing to its socket.
client.write(consolidatedBuffer);
});
// The client can also receive data from the server by reading from its socket.
client.on('data', function(chunk) {
console.log(`Data received from the server: ${chunk.toString()}.`);
// Request an end to the connection after the data has been received.
client.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment