user8244016 user8244016 - 6 months ago 88
Node.js Question

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

hi this is my first time dealing with

long polling
technique for chat application, searching for it in the net I only find how to implement it in
, how can I implement it using only
native JavaScript
? can you guide to some articles or materials on this? thank you

Answer Source

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.

In case you're lazy to read. 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

    // 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!");

app.use(bodyParser.text({ type: 'text/*' }));

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download