Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Handling response with node js and socket io

Handling response with node js and socket io

Problem

I have a scenario in which the web page initially served by HTTP. Upon clicking the submit it will send some data to the server and do few web services which will take long duration. I need to show the response page quickly and after the web service job complete then have to show the result in the same page previously loaded.

Will this possible by processing all the request by http handler and then pass the result by socket io.

I hope to write code some thing similar.

var httpd = require('http').createServer(handler);
var io = require('socket.io').listen(httpd);
var fs = require('fs');
httpd.listen(4000);
function handler(req, res) {
    fs.readFile(__dirname + '/index.html',
        function(err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }
            res.writeHead(200);

            res.end(data);
        }
        );

}
io.sockets.on('connection', function (socket) {
    socket.on('clientMessage', function(content) {
       setTimeout(function () {
           socket.emit('serverMessage', "web service complete");
       }, 5000);


    });
});
Problem courtesy of: Rajeesh V

Solution

I got a solution for my problem, so I am adding this as answer to my own question. I referred socket.io chat application, its useful but there is no complete documentation. For some functions we need to go through the source code. I used a session to identify between the socket and http request and each client. I will paste the code that I found will work .

 var io = require('socket.io');
    var express = require('express');
    var http = require('http');
    var fs = require('fs');
    var connect = require('connect');
    var cookie = require("cookie");
    var app = express();
    var server = http.createServer(app)
    var parseCookie = connect.utils.parseCookie;
    var parseSignedCookie = connect.utils.parseSignedCookie;
    var MemoryStore = connect.session.MemoryStore; 
    var sessionStore = new MemoryStore();


    app.configure(function () {
        app.use(express.bodyParser());
        app.use(express.cookieParser('somesuperspecialsecrethere'));
        app.use(express.session({
            key: 'express.sid',
            store: sessionStore
        }));

    });

    app.get('/', function(req, res){
        fs.readFile(__dirname + '/index.html',
            function(err, data) {
                if (err) {
                    res.writeHead(500);
                    return res.end('Error loading index.html');
                }

                res.writeHead(200);
                res.end(data);
                console.log("SessionID from http: "+req.sessionID);

    setTimeout(function () { //this is for simulating a time taking task
               var sock_id = io.sockets.sockets[req.sessionID];

            io.sockets.sockets[sock_id].emit("getmessage","my mmmmmmmmmmmmmessssssage");

        }, 5000);

            });
    });


    GLOBAL.sio = io.listen(server);
    server.listen(3000);

    sio.sockets.on('connection', function (socket) {

        var hs = socket.handshake;

        socket.on('clientMessage', function(data) {
        console.log("Message from client: "+ data.message);

        io.sockets.sockets[hs.sessionID] = socket.id;
      });

    });

    sio.set('authorization', function (data, accept) {
        if (!data.headers.cookie) {
            return accept('Session cookie required.', false);
        }

        data.cookie = cookie.parse(data.headers.cookie);

        data.cookie = parseSignedCookie(data.cookie['express.sid'], 'somesuperspecialsecrethere');

        data.sessionID = data.cookie;

        console.log('Session Id from socket: ' + data.sessionID);

        sessionStore.get(data.sessionID, function(err, session){
            if (err) {
                return accept('Error in session store.', false);
            } else if (!session) {
                return accept('Session not found.', false);
            }
            // success! we're authenticated with a known session.
            data.session = session;
            return accept(null, true);
        });



        
            
                express WebSocket chat
Solution courtesy of: Rajeesh V

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Handling response with node js and socket io

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×