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?
In HTTP Long Polling the server let you keep an open TCP connection and then you might receive a response from something that changed, or your request might get time out after a while and in both cases you have to re-establish another connection. In other words the client always has a live connection to the server.
Area of usage. Long polling works great in situations when messages are rare. If messages come very often, then the chart of requesting-receiving messages, painted above, becomes saw-like. Every message is a separate request, supplied with headers, authentication overhead, and so on.
When using Node. js, you may exchange code between client and server apps, and you can use JavaScript for the entire development process, allowing for improved communication between back-end and front-end teams.
const poll = async function (fn, fnCondition, ms) { let result = await fn(); while (fnCondition(result)) { await wait(ms); result = await fn(); } return result; }; const wait = function (ms = 1000) { return new Promise(resolve => { setTimeout(resolve, ms); }); }; let fetchReport = () => axios.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With