database updation check in background - javascript

I am working on a tic-tac-toe game which two gamers can play simultaneously, after every click I have to update the database but my problem is that how the other gamer will know that next player has clicked a box and updated the database without page refresh because that will take a long time?

There are a few options.
1) Use AJAX polling every so often. A simple example taken from this link and modified:
function doPoll(){
$.post('endpoint(url or page)', function(data) {
// process results here
setTimeout(doPoll,5000);
});
}
2) Look at web sockets. This post has a good overview: In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?
3) Take a look at SignalR; from the website:
ASP.NET SignalR is a new library for ASP.NET developers that makes
developing real-time web functionality easy. SignalR allows
bi-directional communication between server and client. Servers can
now push content to connected clients instantly as it becomes
available. SignalR supports Web Sockets, and falls back to other
compatible techniques for older browsers. SignalR includes APIs for
connection management (for instance, connect and disconnect events),
grouping connections, and authorization.
This was also a nice overview of several options.

Related

How does Twitter send websockets to it's clients

There are millions of tweets and millions of active users in the Twitter. When a tweet gets like or retweet,how do they send live updates(websockets) of every tweet to its clients?
I think they wouldn't send live updates(websockets) of each tweet to every active user, that would result in (no of active tweets)X(no of active users)=(millions)X(millions)>10^12 live updates in each minute, each user would get millions of updates(of all the tweets) in each minute.
I think the live update of a particular tweet would only be received by the users who are watching that particular tweet.If this assumption is correct,then please tell me, how do they filter clients who are watching a particular tweet and send live updates of that tweet only to those filtered clients?
I was just watching a tweet in the Twitter, I was surprised to see live updates in likes and retweets of that tweet.I haven't seen any social media(like Instagram) giving live updates for every single post of it. I want to implement this method in my social media website.What I had concluded might or might not be correct, but I would request you to explain me, how does Twitter send live updates of every single tweet only to those particular users who are watching it.
To be clear, ONE device has ONE socket connection, to Twitter's cloud.
That ONE socket connection, receives ALL information from Twitter's cloud
new tweets
new likes
new retweets
everything else
all information comes on the ONE socket.
The cloud "figures out" what to send to who.
Is this what you were asking? Hope it clears it up.
The amazing thing is that twitter's cloud can connect to perhaps 100 ? million devices at the same time. (This is an amazing, major engineering achievement which requires an incredible amount of hardware, money and engineers.)
BTW if you're trying to implement something like this for an experiment or client. These days it is inconceivable you'd try to write the server side to achiever this, from scratch. Services exist, which do exactly this - example pusher.com, pubnub.com and so on.
(Indeed, these realtime infrastructure services, are, the basic technology of our era - everything runs on them.)
Here's a glance at the mind-boggling effort involved in Twitter's cloud: https://blog.twitter.com/engineering/en_us/topics/infrastructure/2017/the-infrastructure-behind-twitter-scale.html
Realtime communication or what you refer to as 'live updates' is all a play of various low-level networking protocols. Here's a bit of background on the protocols in general just so you know what you are working with:
A regular REST API uses the HTTP as the underlying protocol for communication, which follows the request and response paradigm, meaning the communication involves the client requesting some data or resource from a server, and the server responding back to that client. This is what you usually see in a regular website that isn't really live but shows or does something following a button click or similar trigger from the user.
However, HTTP is a stateless protocol, so every request-response cycle will end up having to repeat the header and metadata information. This incurs additional latency in case of frequently repeated request-response cycles.
With WebSockets, although the communication still starts off as an initial HTTP handshake, it is further upgrades to follow the WebSockets protocol (i.e. if both the server and the client are compliant with the protocol as not all entities support the WebSockets protocol).
Now with WebSockets, it is possible to establish a full-duplex and persistent connection between the client and a server. This means that unlike a request and a response, the connection stays open for as long as the application is running (i.e. it’s persistent), and since it is full-duplex, two-way simultaneous communication is possible. Now the server is capable of initiating communication and 'push' some data to the client when new data (that the client is interested in) becomes available.
The WebSockets protocol is stateful and allows you to implement the Publish-Subscribe (or Pub/Sub) messaging pattern which is the primary concept used in the real-time technologies where you are able to get new updates in the form of server push without the client having to request (refresh the page) repeatedly. Examples of such applications other than Twitter are Uber-like vehicle location tracking, Push Notifications, Stock market prices updating in real-time, chat, multiplayer games, live online collaboration tools, etc.
You can check out a deep dive article on WebSockets which explains the history of this protocol, how it came into being, what it’s used for and how you can implement it yourself.
Another interesting one is SSE or Server-Sent Events which is a subscribe-only version of WebSockets and restricted to the web platform. You can use SSE to receive real-time push updates from servers, but this would be unidirectional as you can only receive updates via SSE and not really publish anything. Here's a video where I explain this in much more detail: https://www.youtube.com/watch?v=Z4ni7GsiIbs
You can implement these various protocols as required from scratch or use a distributed messaging service like Ably which not only provides the messaging infrastructure of these protocols but also offers other add-ons such as scalability, reliability, message ordering, protocol interoperability, etc, out of the box, which is essential for a production-level app.
Full disclaimer: I'm a Dev Advocate for Ably but I hope the info in my answer is useful to you nevertheless.

Implementing notifications to web app without using Ajax calls to server or so

Case scenario:
I have few 2k concurrent users access to the website with various devices but using their browsers. Once one of them create new topic, all others currently connected should receive a notification (basically I simple update little icon number in app upper right corner).
One way to accomplish this is to have web app keep requesting updates via ajax calls but that overload my slow server with numerous requests.
I use azure to host my web app (written in PHP). There are some services included in my hosting package such as Event Hub, Service Bus etc. What service could I use in order to have my backed talk to a "service" whenever there is a new post, and than to have that "service" talk to my clients (their browsers) and informing them about new notification or any type of data updates?
You're probably looking for websockets. A websocket sets up a connection between the page in the client's browser and your webserver. Through this connection you can push new topics to all connected clients.
It is advisable to decouple the websocket sending process from the request handling of the topic creation. For this you need a background worker which sends websocket notifications when triggered from a processing event.
You can implement this in PHP using ratchet.

How to Keep the same HTTP request in different pages

I have a web application which does downloads of some reports in differents pages in my app, I retrieves the report's data from an external API, I am using AJAX call to get this data. As expected, if the user change the page while the report is being generated the user will not be able to download it, the HTTP request is supposed to be canceled.
There are some solutions in my mind for this problem:
I can open a popup to request the report and keep it open;
I can leave the whole app inside an IFRAME and request the report out of the page;
Or I can change the way how to download the reports doing a queue(Just an idea, does not matter now)...
Is there an alternative way to do that?
Would be possible to keep the HTTP request even when the user change the page?
My scenario is in front-end side(javascript) I don't have access to any back-end. But if there is no way in front-end side, I would like to hear from you any idea.
use onbeforeunload to warn the user that if he navigates away from the page the download will be cancelled
ASP.NET SignalR
ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.
http://signalr.net/
This was the solution my team found out. It's working fine. Our case is only for ASP.NET. But as the own text says, "You may have heard of WebSockets, a new HTML5 API that enables bi-directional...". So, now we can do that.

MVC / websockets in node.js

I'm thinking about building some intranet applications that make use of websockets. I'm currently using Python/Pylons for my web framework on the server, and doing polling to update items in the DOM of the page. Pylons is not well suited to communicate with websockets (IMHO) as it uses a thread per connection. I'm considering using node.js as the server to communicate with the websocket connections from my web application. Here's the "10,000 foot view" of my application:
Pylons delivers the web content (html, css, images, javascript, etc.)
JavasSript on the page application opens up websocket(s) to the node.js server
The node.js server pushes data to the application through the websocket
JavaScript updates the page DOM elements based on the data from the websocket
The data in the case above comes from a MySQL database, which is where my question comes from. I've set up MVC type applications before, and can do the same kind of thing in node.js. However, if I have a long lived websocket open to the node.js server, how does node.js become aware of changes in the Model and push them out to the application? For instance if I want to update totals presented on the web application page, and those totals change due to actions in the system outside of node.js (other web applications), how is node.js notified of those changes? The thing that comes to mind is to have node.js poll the database for various changes and propagate the changes to the various Views. But to me that just sounds like I'm moving my polling from the web application to the node.js server?
Anyone have any ideas, suggestions or pointers on this?
Thanks in advance!
Doug
You can either:
Let the Python scripts notify the node.js application (via a socket or via HTTP)
Or poll from node.js because it is not aware of changes outside it's environment
Polling is considered bad because it doesn't scale. When having a single process that polls does scale because it doesn't need more connections when another user connects. So basically:
// query every second or so
setInterval(function () {
// query database
doSomeDatabaseStuff(function (res) {
// check dirty
if (res.changed) {
// notify all clients
allConnectedSockets.forEach(function (socket) {
socket.send({ msg: "update" });
});
}
})
}, 1000);
This way you have one single process polling the database, and a scalable architecture to notify your connected clients. The database can still be filled from any source.
Sails.js is an MVC framework for node that has the unique distinction of RESTfully routing Socket.io messages in the same way as your Express routes.
Sails currently uses Sequelize, and is configured by default to use mySQL (but also supports SQLite and Postgres). We're switching to a model that lets you choose your own ORM, which will allow us to support JugglingDB (which adds support for Mongo, amongst others)
It also comes bundled with a front-end component, Mast. Mast provides similar functionality to Meteor, in that it allows you to talk directly to the database from the client. If you need to provide more complex functionality, you just add a controller on the backend.
More here: https://github.com/balderdashy/sails

using long polling with facebook graph API (for "real-time" notifications)

I'm looking into implementing a web page to show the user's news feed with real-time updates, without using simple polling to the facebook servers.
after browsing through similar questions:
How to implement facebook line notification?
How does facebook, gmail send the real time notification?
Facebook notification system: Is it polling?
As I understand - long polling (see Comet model) is the most preferable way for me to achieve "push"-like events for when a new post is added to a user's feed.
I'm using javascript, on IE browser (6 and above), and the page is actually stored locally, and not on a server.
I'm aware of the real-time updates subscription graph API, but as I mentioned, my page will run locally, not on a server (not even localhost), that's why long polling seems so attractive at the moment.
My question is - does anyone know if and how long polling (or any other Comet model alternative) is available to use via the Facebook API? or maybe any other suggestions?
Thanks.
I think the only long polling available is for the chat API. Otherwise you're stuck with either real-time updates or using a javascript timer to poll.

Categories