How to implement long polling for React + axios - javascript

I'm using React + axios to talk to the API from the client side. I'm a newbie in JavaScript.
How would I implement long polling so I get near real-time updates on a web page?
Is there a better way to do real-time updates on the page, when backend is a JSON REST API? Should I look into using WebSockets or server side events or long polling is fine?

There is another, potentially better way for your use-case: Server-Sent Events.
SSE, in a nutshell, is a simple GET request to the server from the client - except that the server doesn't close the connection after it's done processing the request. Instead, the HTTP connection is left open and the server is able to write data multiple times to the client, which appear in real-time.
For more info on how SSE compares to Websockets, read Alex Recarey's answer to "WebSockets vs. Server-Sent events/EventSource" in SO.

Related

Sending JSON to all online clients without them making a request. [NodeJS]

I'm building a website, and one of the features is a public chat that anyone online can use. When a message is entered it is sent to the server and then saved to a SQL database. How could I relay this information to all the online clients without them making a request to the server? I've thought about having all clients make a request to the server every 500ms or so but I feel that would be incredibly inefficient. Any suggestions?
What you're looking for is typically called "server push" where the server can unilaterally send data to the client without the client having to "poll" or repeatedly ask for new info.
The two general technologies for server push these days are webSockets and server-sent events (SSE). In both cases, the client initiates a connection to the server and that connection is held open so that the server can send data to the client whenever it wants to without the client having to specifically poll for that data.
A webSocket is a full, two-way data channel. Either client or server can send data in either direction.
SSE is a one-way channel, the server can send data to a listening client.
You can see these articles on comparing the pros/cons of each.
WebSockets vs Server-Sent Events - ably.com
Server-sent events vs. WebSockets - logrocket.com
Difference between server sent events and Websockets in HTML5 - geeksforgeeks.org
And, there are dozens of other articles here.
You may also want to be aware of socket.io which is a widely used layer built on top of webSockets that adds more features than either of these have (a named message layer, auto-reconnect, message acknowledgement, direct message response, built-in JSON support, etc...).
Any of these can do what you're asking for. Which of these to choose really depends upon the details of your requirements.
Try making a WebSocket server. There is ws package for Node.js, and alternatively socket.io. However if your client is a web client, you can use socket.io for easy-use and setup.

socket io - How does it know if a data changed in DB?

In my Angular5 / NodeJS web app, we have a dashboard that needs real-time data.
If there is any data change in the DB, we want it to be reflected in the front end immediately. Currently, we are reloading the data at regular intervals (say 30 seconds).
Can socket.io help to achieve this?
Not sure, how does it know if there are any data changes in the DB?
You can use SSE (Server Sent Events) a feature in HTML5.
Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.
Here is simple example
As the SSE are unidirectional it will save efforts and enhance performance, as you just want to send db updates to frontend i.e. single direction only.
Hope this will help you.

Alternate of server polling?

As we know, if running application also manage sessions in main memory then is there any way for server to send responses to all web clients/browsers for new recorded data in a database.
Remember: I have not made any request to server or polling to server for new records update..
Let server make responses without web request..
Objective :
No all web browsers making request or polling to server for every certain interval therefore reducing the performance issue with the application memory..
Am just against of making so many ajax calls from every web client..
Need your ideas from your past, if experienced similar..
read about websockets and socket.io.
basically with socket.io you have a connection open between browser (client) and server and server can send data which the client than receives as an event.
the client doesn't need to send a request to get that data, only open the web socket connection.
you can look at socket.io chat example: http://socket.io/get-started/chat/
WebSocket is the best and easy solution if you don't want to go through the hassle to learn Angular or others.
Both server-side and client-side can build WebSocket, and it acts as a bridge to transmit data back and forth.
I just created an easy solution for this.
Please check my new library wsm - WebSocket Manager, it works for both server-side and client-side.
Websocket Server can be built easily; this library includes several useful features.

Server Side Events + Client Side Events vs Websocket

I am updating an old system that used to use an ajax polling mechanism. The script would periodically call the back-end looking for updates, and rarely the user would make an ajax request to send data. I first wanted to use Web Sockets because I could instantly get the data from push events, and because the connection stays open. I then read about Server Side Events, and how it is one directional. This fits exactly what I need because the browser is just waiting for events. However, there are rare cases when the user can send data. Is there an alternative to Server Side Events, where I can keep a connection open to send data back to the server? Is it better to use SSE + AJAX, SSE + (Alternative Way), or just a web socket (Even though data is rarely sent back to server)?
Thank you
This is the best explanation for SSE and its flexibilty
Server-Sent Events vs. WebSockets
Why would you choose Server-Sent Events over WebSockets? Good question.
One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.
SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.
I had built a chat application using sse and ajax for my site.I would suggest sse + ajax would be way to go if there is only stream updates and very few updates from client to server for that you can use the ajax part
Only problem that I found is its lack of support across browsers .And if you want to know more in depth about sse ask specifically what you want
Browser Support List
As you usage is mostly server pushing to client, I would recommend a combination of Server-Sent events for the push from server to client and AJAX for the other way around.
You should definitely read this article to get to a decision:
http://streamdata.io/blog/push-sse-vs-websockets/
This will give you pros and cons of using Server-Sent events versus WebSocket.

Get Refesh Data From The Server

How can i get latest or fresh data from server (if in server happened new event (for example there are 2 users x,y and x send messages to y and y get this message without refreshing page ) )?
I don't want to use setInterval because it repeats all message again and again. Is there any Technique that can i use for this ?
I heard about Ajax that technique need to send request to the server but i want when happen an event in the server and webpage get it without refreshing..
The first technique is the long polling, which sends request to the server and waits until the server sends something, for example the new message. You must re-send requests to the server each time you get a new message or your request is time out. This technique uses AJAX.
Long polling PHP example - How do I implement basic "Long Polling"?
The second is web sockets, https://en.wikipedia.org/wiki/WebSocket
this stackoverflow question deals with the implementation of websocket.
socket.io has a demo of chat application.
If you looking for bidirectional full duplex method then go for WebSockets but for just polling data from server you can use Server Sent Event as well. Adding reference links for both:
WebSocket:
http://html5demos.com/web-socket
http://en.wikipedia.org/wiki/WebSocket
HTML5 Websockets for Realtime Chat app?
SSE:
http://www.html5rocks.com/en/tutorials/eventsource/basics/
Examples:
SSE: http://demo.howopensource.com/sse/

Categories