npm install json-socket
var net = require('net'),
JsonSocket = require('json-socket');
var servers = ['localhost'];
Next, we'll create a function that takes a socket (instance created with net.Socket()), decorates it using the json-socket so it easily handles JSON data, and tells it all the events we want it to listen for. Whenever the server responds, we'll handle the results with a closure:
var initSubscriptions = function(socket) {
socket.on('connect', function() {
socket.sendMessage({name: 'James'});
//handles a message returned from the server
socket.on('message', function(message) {
console.log('Server responds: ' + JSON.stringify(message));
});
//'close' is emitted whenever a server closes
socket.on('close', function() {
console.log('Server Disconnected!');
});
});
};
Now we simply loop through all of our server names, open a socket for them and finally create subscriptions using our initSubscriptions function
var nodes = [];
servers.forEach(function(nodeName) {
var socket = new JsonSocket(new net.Socket());
socket.connect(42424, nodeName);
initSubscriptions(socket);
nodes.push(socket);
});
We'll have the client and server communicate through port 42424 in this example, though you can easily modify this so that it listens on a free port of your choosing. The nodes array will hold the actual socket instances that represent the TCP layer through which we communicate with our servers.
var net = require('net'),
JsonSocket = require('json-socket');
var server = net.createServer();
server.listen(42424);
server.on('connection', function(socket) {
console.log('client connected');
socket = new JsonSocket(socket);
socket.on('message', function(message) {
socket.sendMessage('Hello ' + message.name);
});
});
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)