Simple messaging protocol for node's net socket
npm install net-socket-messaging``sh`
npm install net-socket-messaging
Implementation of a simple messaging protocol by monkey-patching a net.Socket.
The protocol is the simplest I could think of:
- The head consists of 4 bytes which encodes an unsigned 32 int written in little endian.
- The body is a string of bytes which encodes a string in utf8 and whose byte length is defined by the head.
`jsregisterSocket
const socket = require("net").connect();
// monkey-patches a net.Socketsend
// with the method and the message event.message
require("net-socket-messaging").monkeyPatch(socket);
// Once monkey-patched, the socket should not be
// directly used to read or write data.
const message = "foo";
socket.send(message);
// The event is emitted only if there is a`
// least one listener registered.
socket.on("message", (message) => {
console.log("Received:", message);
});
* socket : the socket to monkey-patch.
* Returns : I'm not a big fan of artificial chain callings, you should assume your side effects!
* Returns : the maximum length of messages.
Send a message through the net.Socket.
* message : the message to send.256 * 2^20
Sending a string longer than characters will fire an 'error' event on the socket. There is two motivations for this limit:2^32
1. It ensures that the body is under 1GiB (as a single utf16 character may be encoded in as much as 4 bytes). There is two reasons why we want to limit the length of the body. First, the maximum number encoded by the head is . Second, the stream.readable.read(size) does not accept a size argument greater than 2^30.2^53 - 1
2. JS engines impose a limit to the length of strings. Although the ECMAScript 2016 specification states that the maximum length of a string is , many engines opted for a smaller limit. A length of 256 * 2^20 is a conservative limit which most JS engines support.
* Returns | : null if the message is too big to be sent and a as per the return value of new.Socket.write(buffer).
Emitted when a message has been fully received.
* message : the received message. Neither the length of the body nor the length of the message is checked. If the engine supports it, a message as long as 2^32` characters could be provided.