A Mutable Log

A blog by Devendra Tewari


Project maintained by tewarid Hosted on GitHub Pages — Theme by mattgraham

Node.js client to server with socket.io

Socket.io is usually employed by browser apps communicating with a Node.js server application. It is however possible to create a client in Node.js if you need to call the same server application. It is also possible for the server to return values by calling a function that the client passes to it.

You’ll need to install socket.io and socket.io-client using npm as shown below. Additionally, we also use express for serving static HTTP content.

npm -g install socket.io socket.io-client express errorhandler

This is how a client connection can be established

var io = require('socket.io-client');
var serverUrl = 'http://localhost:8080/ns';
var conn = io.connect(serverUrl);

var p1 = 'hello';
conn.emit('call', p1, function(resp, data) {
    console.log('server sent resp code ' + resp);
});

The namespace ns is used for communicating with the server. Client emits the event call with parameter p1, and a function parameter that receives a response code and additional data.

This is how a server can serve the client above

var http = require('http');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
var errorhandler = require('errorhandler');
app.use(errorhandler()); // development only
var server = http.createServer(app);

var io = require('socket.io').listen(server);
var ns = io.of('/ns');
ns.on('connection', function (socket) {
    socket.on('call', function (p1, fn) {
    console.log('client sent '+p1);
        // do something useful
        fn(0, 'some data'); // success
    });
});

server.listen(8080);

Socket.io makes event-based communication really easy.