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.
Related
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.
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.
How does a site programmed using TCP (that is, someone on the site is connected to the server and exchanging information via TCP) scales compared to just serving information via AJAX? Say the information exchanged is the same.
Trying to clarify: I'm asking specifially about scale: I've read that keeping thousands of TCP connections is resources (which?) demanding, as compared to just serving information statically. I want to know if this correct.
WebSockets is a technology that allows the server to push notifications to the client. AJAX on the other hand is a pull technology meaning that the client is sending requests to the server.
So for example if you had an application which needed to receive notifications from the server at regular intervals and update its UI, WebSocket is more adapted and much better. With AJAX you will have to hammer your server with requests at regular intervals to see whether some state changed on the server. With WebSockets, it's the server that will notify the client for some event happening on the server. And this will happen in a single request.
So I guess it would really depend on the type of application you are developing but WebSockets and AJAX are two completely different technologies solving different kind of problems. Which one to choose would depend on your scenario.
Websockets are not a one-for-one with AJAX; they offer substantially different features. Websockets offers the ability to 'push' data to the client. AJAX works by 'pushing' data and returning a response.
The purpose of WebSockets is to provide a low-latency, bi-directional, full-duplex and long-running connection between a browser and server. WebSockets opens up possibilities with browser applications that were previously unavailable using HTTP or AJAX.
However, there is certainly an overlap in purpose between WebSockets and AJAX. For example, when the browser wants to be notified of server events (i.e. push) either AJAX or WebSockets are both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets which would definitely scale better in this scenario. On the other hand, if you need to work with existing frameworks and deployed technologies (OAuth, RESTful API's, proxies, etc.) then AJAX is preferable.
If you don't need the specific benefits that WebSockets provides, then it's probably a better idea to stick with existing techniques like AJAX because this allows you to re-use and integrate with an existing ecosystem of tools, technologies, security mechanisms, knowledge bases that have been developed over the last 7 years.
But overall, Websockets will outperform AJAX by a significant factor.
I don't think there's any difference when it comes to scalability between WebSockets and standards TCP connnections. WebSocket is an upgrade from a static one way pipe into a duplex one. The physical resources are the exact same.
The main advantage of WebSockets is that they run over port 80, so it avoids most firewall problems, but you have to first connect over standard HTTP.
Here's a good page that clearly shows the benefits of the WebSocket API compared to Ajax long polling (especially on a large scale): http://www.websocket.org/quantum.html
It basically comes down to the fact that once the initial HTTP handshake is established, data can go back and forth much more quickly because the header overhead is greatly reduced (this is what most people refer to as bidirectional communication).
As an off note, if you only need to be able to push data from the server on a regular basis, but you don't need to make many client-initiated requests, then using HTML5 server-sent events with occasional Ajax requests from the client might be just what you need and much easier to implement then the WebSocket API.
I have a very simple question about ajax.
If I'd like to refresh a particular area of my site I supose ajax would be the best way.
But is there anyway instead of having a javascript periodically checking for changes on the server, the server would send the data when a given event would happen?
What I'd like was the client not needing to send requests periodically but instead the server would only send the info to the client which in turn would have some kind of event listener.
Thanks in advance
Yes, this can be done. It is referred to as "push" or "push streaming".
Here is one website that offers the ability to do this: InstantPush. And a brief quote from their home page:
"InstantPush is used to make web pages
and mobile phones go live. They will
instantly be updated in real time when
a change occurs at the server side.
Standard web communication makes
updates pass firewalls and proxies.
Without any modules at the client
side!
InstantPush has been used since 2001,
before "Ajax was invented". It is
probably the First Ajax Push
Framework.
InstantPush is leading the market in
northern Europe."
Here is another company offering this technology: LightStreamer. And a quote from their home page:
"Lightstreamer is a scalable and reliable Server for pushing live data to Rich Internet Applications
Based on the Comet and Real-Time Web
paradigms, it streams real-time data
to any Web browser and client
application. HTML, HTML5, AJAX, Flex,
Silverlight, Java, .NET, iOS, Android,
and BlackBerry applications, can
easily receive live data from
Lightstreamer Server.
Lightstreamer has been used in many
mission-critical production systems,
where scalability, low network impact,
bandwidth management, adaptive
streaming, and other advanced
features, have proven fundamental."
This cannot be done because the http protocol works by sending a request and receiving a response from the server, hence the server cannot a response without receiving a request.
No this cannot be done. A server's job is to serve up results from a request, one that it must have to begin with.
That is not possible using traditional HTTP. You can, however, use long polling or one of its siblings to simulate push behaviour.
I think that websockets is the way to go, but is not supported for all browsers yet.
I used them with ruby and chrome and was pretty easy.
this is indeed a difficult ask where server broadcasts/pushes data to clients without being requested. HTTP is stateless and even if browser is a registered client, it still needs to request either through code or through some tags like meta refresh. New but still not so stable options are Comet or websockets.
Answer is Comet rather than websockets. YES, it is possible.
Another way is using Browser plugin.
This is an except from wiki page at Push Technology
* Apple Push Notification Service
* BOSH
* Comet
* Client–server model
* File transfer
* Pull technology
* Push Access Protocol
* Push e-mail
* Reverse Ajax
* Streaming media
* WebSockets
I'm prototyping a realtime notification mechanism using http over port 80. The aim of the project is to allow a Flash application to respond to an event on a remote server quickly (specifically an inbound phone call being connected to a phone next to the computer.) Polling is one approach, but is too slow. Currently I use a socket connection to get low latency notification of the events on the server, which works well but isn't firewall friendly. I don't want to install anything except Flash, or Silverlight on the client. Cross compatibility of browsers isn't a concern - in this application I can specify what browser the client uses but IE is preferred.
I've made a server HttpHandler in .NET which never closes the connection and sends the "events" to the client by writing out bytes to the http response stream (ConnectedClientContext.Response.OutputStream.Write etc) and I have a .NET client application which can read these messages okay.
My Question:
Can I receive the bytes from the server over HTTP as they arrive using JavaScript, Flash or Silverlight? So far I can only find a way to get notified of the "download progress" and don't get the actual bytes until the response is closed - I want them as they arrive.
Best Regards,
Daniel
I don't know about Flash but in Javascript (by which you mean in browser) and Silverlight you are limited pretty much to the http protocol.
You can use the AJAX Http Streaming pattern. The basic ideas which is different from what you are trying is that as soon as data is available outstanding request ends and a new is immediately initiated asychronously, mean while your client process the newly arrived data.
Silverlight gives you more options since is HTTP stack is purely asynchronous but you can get your hands on the stream to you as soon as data starts to arive by setting the HttpWebRequest.AllowReadStreamBuffering to false. (Unlike XmlHttpRequest which always buffers).
it's very easy to use the Comet ideas for notifications. you don't even have to use a comet-specific framework. simply do an ajax request with a callback on answer, wrap this on a loop and you have an event loop, just like a GUI app. on the server side, don't bother answering the request until there's either an event, or a timeout (which is just a 'null' event).
Flex and Flash have several AMF/XML remoting libraries available that support data pushing. I would certainly look into that.
http://raghuonflex.wordpress.com/2008/04/17/data-push-in-flex-with-backend/
These libraries use a Comet - like implementation to achieve this.