HTML5 Server-Side Event: EventSource vs. wrapped WebSocket - javascript

Is the HTML5 Server-Sent Events (SSE) API just a restricted, event-based API on top of HTML5 WebSockets?
It seems to me that an EventSource is just a WebSocket that:
Cannot .send() data
Uses the text/event-stream format
Fires dynamically-named (server-defined) events instead of onmessage
The idea of the web server pushing events down to client devices is quite intriguing. Does this API have any traction?
I imagine the async event model would work beautiful when couple with Node, but not seeing a lot of use cases for this in my ASP.NET world.

Server Sent Events is useful in applications that only needs server push while Web Sockets are good for applications that needs fast communications in both directions.
Examples where Server Sent Events are a good solution are:
Stock Value changes
News feeds
Server Sent Events do some more things that is not built-in in Web Sockets, such as automatic reconnection and eventIDs.
Server Sent events also has broader web browser support as of today, with support in Safari (only support older drafts of Web Sockets) and Opera (has Web Sockets disabled by default, and uses an older draft).
Read more about Server Sent Events on Stream Updates with Server-Sent Events.

In addition to what Jonas said, the protocols are entirely different.
The WebSocket Protocol (RFC 6455) starts as an HTTP connection, then uses a handshake to upgrade the connection to the new protocol. This is a binary protocol that uses framing, message types, and more.
Server-Sent Events is a long running HTTP request that stays open. The server sends messages in a simple text-based format (UTF-8 encoding), delimited by \n\n. A message has fields event (the event type), data, id, and can optionally include comments.
One major difference is the security model. With WebSockets, the default is to let anyone connect. Rejecting a connection must be done on the server side, based on the Origin header.
SSE on the other hand, is closer to HTTP and uses same-origin policy. By default you can only make requests to the same host and port. In the future it will be possible to use CORS to make cross-domain SSE requests. As of today, browsers have not implemented this yet.
The two protocols take different approaches, as they solve different problems.

Related

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.

Can a browser communicate with another browser on the same network directly?

I'm playing around trying to find a way to communicate between two browsers on the same network to establish WebRTC without a server roundtrip (no STUN/ICE/TURN). Basically an alternative to the approach found here, where the "handshake" is done via copy/mail/pasting.
After sifting through all the cross-browser-communication examples I could find (like via cookies or WebTCP) plus a bunch of questions on SO (like here), I'm back to wondering a simple thing:
Question:
If Alice and Bob visit the same page foo.html while on the same network and they know each others' internal assigned IP addresses, are there any ways they can communicate purely with what is available on the browser?
This excludes non-standard APIs like Mozilla TCP_Socket_API, but other than that all "tricks" are allowed (img tags, iframes, cookies, etc.).
I'm just curious if I can listen to someone on the same network "broadcasting" something via the browser at all.
Edit:
foo.html will be on static server, no logic, no ICE, no shortcut.
Edit:
Still not a solution but a websocket server as Chrome extension comes closer. Example here: almost pure browser serverless WebRTC
Yes, you can establish a direct connection between two browsers over the local network using WebRTC. It requires the use of ICE, but that does not mean that an outside STUN or TURN server is needed. If the browsers are on the same network, ICE will succeed with only the local candidates of each browser.
STUN/TURN is needed only in order to guarantee that two endpoints can establish a connection even when they are in different networks and behind NATs.
In fact, if you use most of the WebRTC example applications (such as apprtc) with two browsers connected in a local network, ICE is most likely to select and use the pair of local addresses. In this case a channel allocation on a TURN server will be made, but it will not get used.
In your WebRTC application, you can disable the use of STUN/TURN by passing empty iceServers when you create the PeerConnection.
While the MDN documentation lists WebSocketServer as a client API, I don't think this is accurate (maybe they wanted to document there how to write a server).
At the moment, I know no standard way to create a server socket on a web browser. I know a couple of attacks to scan the local network but most of them rely on an active server outside the network, that is you connect to a server and get JavaScript back which opens a WebSocket connection. Via that connection, I can take full control over the client and have it open more WebSockets with local IP addresses to scan the internal network.
If internal web sites don't implement CORS correctly (see here), I can access all internal web sites where the current user is currently logged in. That is a devious attack vector which allows external attackers to browser internal documents without cracking anything. This page has a demo of the attack.
Even Flash won't let you create a server socket.
If you allow a Java applet and the Java version on the client is very old or the user blindly clicked "OK", then you can create server sockets.
Related:
Socket Server in Javascript (in browsers)?
This could be explained easily. The answer is it's not possible. In order for alice and bob to communicate at all without a third-party, at least one of them needs to be listening for incoming connections. Not possible using a standard web browser alone.
You can take a look at this
https://github.com/jed/browserver-client
I think that you can easily create an http server with javascript and send messages from one browser to another
With Nodejs you can achieve the same.

How does WebSockets scale compared to standard HTTP?

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.

Websocket library for browsers?

Are there websocket libraries (like ajax for jquery) I can use on the browsers with fallback to ajax long polling?
I found that Socket.IO implements a weird, arbitrary layer over the WebSocket protocol. I'd rather just pass raw data back and forth, so for my project, I went with web-socket-js.
web-socket-js works similarly to Socket.IO in that it reverts to using Flash sockets if WebSocket support is unavailable. Thus, it works in all the major browsers that support Flash (I tested this myself).
Just make sure you open port 843 in your firewall or you'll get a Flash security policy error. You'll probably need a script to listen on port 843 as well...I used em-websocket for the socket server, and in its readme I believe is a link to a Perl script that provides this.
Library with WebSockets support and fallback long polling solution would probably depend also on server side technology and not only browser client. Try to look at socket.io for example.
I have been using SignalR for the last several months, and it is awesome. It does what Socket.IO does, but maybe even better. It degrades as follows: Web Sockets, Server Sent Events, Forever Frame, AJAX long polling. Only works with .NET though.
https://github.com/SignalR/SignalR/wiki/Faq
Yes, you'll need server support for that as well. Kaazing WebSocket Gateway supports a very fast emulation/Polyfill. If you have a plugin like Flash it may use that (opportunistic optimization), but if you don't it emulates WebSocket with encrypted streaming, which is a lot more efficient than long polling. It comes with SSE and Cross Document Messaging support and emulation as well, as well as many higher level protocol abstractions (JMS/Stomp, XMPP, etc.)
Union Server has WebSocket support with fallback to comet-style AJAX communication. Union is a platform for creating connected applications, such as online multiplayer games.
http://www.unionplatform.com

Can I receive a stream over HTTP with JavaScript, Flash, or Silverlight?

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.

Categories