javascriptnode.jslong-polling

How to use long polling in native JavaScript and node.js?


I need to implement long polling for a chat application. I've searched around, but I only find how to implement it in JavaScript using JQuery. How can I implement it using only native JavaScript and Node.js? Can you guide me to some relevant articles or materials?


Solution

  • Q: How to do long polling in native Javascript in nodeJS?

    A: I guess first of all you need to understand how the long polling model works. If you haven't had any clue then the RFC-6202 specification is a good starting point.

    It is about the client sending a request to the server and waits until a response is returned.

    From the specification we know that first the client will have to issue a http request which has an infinite or at least a high timeout value. Then the server, which is your nodeJs application is expected to stash all incoming requests into a data structure, basically a holding area. Your application will essentially hold on all the response object until an event gets triggered, then you reply to the responses appropriately.

    Consider this Pseudo code:

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    
    var requestCounter = 0;
    
    var responses = {
      /* Keyed by room Id =*/
      "room_abc" : [ /* array of responses */]
    };
    
    app.get('/', function (req, res) {
        requestCounter += 1;
    
        var room = /* assuming request is for room_abc */ "room_abc";
    
        // Stash the response and reply later when an event comes through
        responses[room].push(res);
    
        // Every 3rd request, assume there is an event for the chat room, room_abc.
        // Reply to all of the response object for room abc.
        if (requestCounter % 3 === 0) {
            responses["room_abc"].forEach((res) => {
                res.send("room member 123 says: hi there!");
                res.end();
            });
        }
    });
    
    app.use(bodyParser.text({ type: 'text/*' }));
    app.use(bodyParser.json());
    
    app.listen(9999, function () {
        console.log('Example app listening on port 9999!')
    })
    

    It is relatively time consuming to write a working example here but the code above is a good example of how you can implement long polling in NodeJS.

    If you have postman installed or curl you can do HTTP calls to http://localhost:9999/ using method GET. You should noticed that on the first two calls you won't get a response and it is when you fired the 3rd one then you'll receive a response for all previous and current calls.

    The idea here is you stash the request's response object first and when an event comes through, assuming on every 3rd HTTP call, you then loop through all of the responses and reply to them. For your chat application's case, the event that triggers a response would probably be when someone fires off a message to a chat room.