Skip to content Skip to sidebar Skip to footer

Tcp/ip Communications With Nodejs For Multiple Write Messages

I am working on building a distributed caching system using python over TCP/IP and I have implemented the TCP SERVER using python and I am creating TCP client libraries for Python,

Solution 1:

Idea

When dealing with async using sockets, the idea would be to tag the request with an identifier, and register a handler for that identifier, and when response is received, we match with registered identifiers. This is because we do not conceptualize sockets as request/response.

Here is a sample reservoir module (reservoir.js):

var net = require('net');

module.exports = {
    client: {},
    connect: function(port, host, then) {
        var $this = this;
        var client = net.Socket();

        client.connect(port, host, function(){
            then && then();
        });

        client.on("data", function(data) {
            $this._process(data);
        });

        this.client = client;
        returnthis;
    },
    get: function(key, then) {
        var $this = this;
        $this.client.write(key, function() {
            $this._handle(key, then);
        });
        returnthis;
    },
    _handlers: {},
    _commands: ['GET', 'SET', 'DEL'],
    _handle: function(key, handler) {
        //remove commands from the key, because server doesn't return them (you can check here if its a valid command)var keyParts = key.split(' ');
        keyParts.shift();

        this._handlers[keyParts] = handler;
    },
    _process: function(data) {
        var response = JSON.parse(data.toString());
        var handler = this._handlers[response.incoming_message];
        if (handler) {
            if (response.message) {
                handler(null, response.message);
            } else {
                handler(new Error(response.error), null);
            }
        }
        delete this._handlers[response.incoming_message];
    }
};

Here we are registering each callback with the associated key - so when we receive the data, we fire up the specific handler.

After all the abstraction in the module file, here is how it can be used:

var reservoir = require('reservoir');
var onConnect = function() {
    console.log("\nConnected.");
    reservoir.get('GET pk_movie', function(err, response) {
        console.log(response);
    });
}
reservoir.connect('3000', 'your-host.com', onConnect);

Hope that helps!

Post a Comment for "Tcp/ip Communications With Nodejs For Multiple Write Messages"