Search code examples
javascriptwebsocketserver-sent-events

Server sent event vs web sockets?


I'm working on a web app that is accessible to users via multiple platforms from smartphones to desktops which needs to sometimes make a communication between two clients for example if I want my friend to join my network I'd send him a friend request but I want that request to be seen by my friend without him having to refresh the page.

In this scenario which would be a better choice? And also since I want this to work on as many platforms and browsers as possible which has more browser support? Is there a better option?


Solution

  • Some things to keep in mind when making this choice.

    • Attempting to fetch content over a WebSocket connection is a poor design decision because WebSockets is a different protocol nested inside an HTTP connection and it can't leverage caching (neither the browsers nor CDNs).
    • Some older proxies won't pass on a Websocket connection unless its hidden within a secure connection while Server Sent Events remains an HTTP connection and won't suffer from this.
    • Neither WebSockets nor SSE are supported in the native Android browser until 4.4 (when they switched to using Chrome) - thus if you're considering a hybrid mobile app, you will need a fallback such as SocketIO since, as of this writing, 4.4 is only 20% of the market and hybrid apps use the native Android browser.
    • WebSockets is the most battery efficient protocol for mobile devices, since all other options require many HTTP connections and it is the repeated negotiating of the headers that will burden the cpu and drain the battery.

    Another option may be notifications. All mobile devices now support notifications that can be targeted to an App and a number of browsers have as well. In all cases a connection already exists from the client to the messaging center (Apple, Google, Microsoft, etc) and all notifications are sent over this channel.

    Here's a good overview of WebSockets vs. SSE: http://www.html5rocks.com/en/tutorials/eventsource/basics/