Created
February 27, 2020 08:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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