WebSocket and IoT

Introducing WebSocket-Based Real-Time Monitoring System for Remote Intelligent Buildings

867693.fig.002

The core idea of the proposed system is to enable wireless Web-based interactions with sensor gateways and WebSocket and Web server for monitoring the remote intelligent buildings. Figure above shows the proposed WebSocket-based monitoring system for WSNs of remote intelligent buildings in WSNs. This WebSocket-based monitoring system is composed of three points of view in order to reduce the complexity: WSNs of remote intelligent buildings, WebSocket-based real-time monitoring, and storage of the monitoring sensor data.

WebSocket

HTML5 WebSocket defines a bi-directional, full-duplex communication channel that operates through a single TCP socket over the Web, it provides efficient, low-latency and low cost connection between web client and server, based on WebSocket, developers can build scalable, real-time web applications in the future. Section below is the official definition of WebSocket copied from IETF WebSocket protocol page:

The WebSocket protocol enables two-way communication between a user agent running untrusted code running in a controlled environment to a remote host that has opted-in to communications from that code.  The security model used for this is the Origin-based security model commonly used by Web browsers.  The protocol consists of an initial handshake followed by basic message framing, layered over TCP.  The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling).

WebSockets come after many other technologies that allow servers to send information to the client. Web applications that use Comet/Ajax, push/pull and long polling all do this over HTTP. Other than handshaking the Upgrade Header, WebSockets is independent from HTTP.

JavaScript API

WebSocket Events

The WebSocket API is still a draft, but the major modern browsers have already implemented most of the functionality, and even Microsoft has a prototype implementation in the works for Internet Explorer.

This specification defines an API that enables Web pages to use the WebSocket protocol for two-way communication with a remote host.

See the Pen WebSockets Demo by ji pengxiang (@jipengxiang) on CodePen.


The WebSocket API Editor’s Draft

The JavaScript added as part of the HTML5 specification allows for fairly simple use of the WebSocket protocol by developers. Amongst read-only connection details such as ‘url’, ‘protocol’ and ‘readyState’ the WebSocket interface defines four event handlers and two methods:

[Constructor(in DOMString url, in optional DOMString protocols)]
[Constructor(in DOMString url, in optional DOMString[] protocols)]
interface WebSocket {
  readonly attribute DOMString url;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSING = 2;
  const unsigned short CLOSED = 3;
  readonly attribute unsigned short readyState;
  readonly attribute unsigned long bufferedAmount;

  // networking
  attribute Function onopen;
  attribute Function onmessage;
  attribute Function onerror;
  attribute Function onclose;
  readonly attribute DOMString protocol;
  void send(in DOMString data);
  void close();
};
WebSocket implements EventTarget;

These simple functions make it easy to get started with WebSockets, a simple example being the echo test hosted onwebsocket.org:

websocket = new WebSocket('ws://echo.websocket.org');

websocket.onopen = function(event) {
  websocket.send('hello from client');
};

websocket.onmessage = function(event) {
  console.log(event.data);
};

Here, the client attempts to connect to a WebSocket, should the connection be successful, it sends a message to the server. The echo service example simply repeats messages back across the connection, so on receipt of the message, would send the same message back to the client, which would then trigger the ‘onmessage’ function and print the message out in the console. This example could be built upon as I have shown below by swapping out console logs for DOM alterations; or even further by negotiating the exchange of client messages as a chat application as shown in my examples.

Server-Side

WebSocket servers are also relatively simple to set up. There is a vast collection of libraries, frameworks and even some native support spanning languages including:

Having some experience with Node.js and finding Ruby syntax somewhat difficult to grasp, for my prototypes I chose to make use of the Node WebSocket Server package by Micheil Smith.

Node WebSocket Server is a near specification compliant implementation of the server-side WebSocket Protocol. It is built on top of Node.js as a third-party module, and is designed to support various versions of the WebSocket protocol – which is currently still an IETF Draft.

Node WebSocket Server

The server’s main roles amongst other things are to accept (or reject) clients, maintain a unique identifier for each connection and to listen for and broadcast messages, the core concept being to manage the rapid exchange of data between nodes.

Protocol

WebSocket Lifecycle

When loading a webpage geared for WebSocket interactions, initially, a standard HTTP connection is used, to load the mark-up, styling and JavaScript. The JavaScript then sends a HTTP request asking to upgrade to use the WebSocket protocol, passing along some keys. After a complex handshake that ensures both sides fully support WebSocket- the server sends a HTTP response returning more keys and confirming the connection. This handshake is for the most part handled internally by the WebSocket JavaScript API, and once it is complete, the full power of the protocol is unleashed.

Once the connection is established there is no HTTP header overhead on each packet, the protocol overhead is in fact only two bytes per packet. Additionally, there’s no huge XML encode / decode overhead either, so this is a great transport for low-latency data like gaming player positioning updates or speech.

Whilst mainstream adoption of the protocol amongst modern browser vendors has been great, recent discoveries found that the WebSocket protocol is vulnerable to attacks. Adam Barth demonstrated some serious attacks against the protocol that could be used by an attacker to poison caches that sit in between the browser and the Internet. As a result of this, major vendors including Mozilla and Opera disabled WebSockets functionality by default to protect users until the protocol is fixed. However, at the time of writing, the protocol has now been patched and no doubt vendors will implement the changes and re-enable the protocol by default soon.

WebSocket Demos

Here you will find an aggregated list of WebSocket demos from all over the Web.

Thumbnail of Echo Test

Echo Test

Test a WebSocket connection from your browser against our WebSocket echo server.

http://www.websocket.org/echo.html

Thumbnail of Kaazing.me

Kaazing.me

Several examples of WebSocket together on the one page. The bar along the bottom of the screen lets you connect to Google Chat over WebSocket.

Original link

Thumbnail of Mr. Doob's Multiuser Sketchpad

Mr. Doob’s Multiuser Sketchpad

A shared sketchpad that everyone can draw on at the same time. Websockets are used to keep up with the position data shared between users.

Original link (Demo)

Original link (Article)

Thumbnail of Rumpetroll

Rumpetroll

Norwegian for “tadpole”, swim around with other rumpetrolls. WebSockets communicate positional data between all users.

Original link

Thumbnail of WordSquared

WordSquared

A massively multiplayer online Scrabble-like word game.

Original link

WebGL Aquarium

This is a 100% HTML5, WebGL and JavaScript. Each of the 8 machines is running Chrome. They communicate using WebSockets to coordinate the differenct screens.

Original link

The WebSocket Difference

A video that visually demonstrates the performance improvements you get by using WebSocket.

Original link

Video Sync with WebSocket

Shows a single controller controlling the video that all connected users are watching.

Original link

The following examples created to demonstrate the basic functionality of WebSockets, they are for the most part written in raw JavaScript with the occasional dash of jQuery and Node.js server-side. All source code is available on Github.

  • ChatA basic anonymous multi-user chat relay via WebSockets.
  • DateA script that pushes the current server datetime out to connected clients.
  • EchoAn echo responder.
  • TwitterPiping the Twitter Streaming API public timeline sample through WebSockets.

The WebSocket protocol is blocked by the UWE proxy. Please mark off-site.

WebSockets in Action

The following websites demonstrate the use of WebSockets in production environments, for a wide range of applications including massively multiplayer gaming, sketching and multiuser synchronising of data.

  • Kaazing

    Various examples of WebSockets being used for the retrieval of real-time data.

  • Multiuser Sketchpad

    A shared sketchpad that everyone can draw on at the same time. WebSockets are used to keep up with the position data shared between users.

  • noVNC

    A full VNC client implemented using HTML5 Canvas and WebSockets.

  • Rawkets

    A massively multiplayer game in which you can shoot and interact with other players, in real-time, in space! It uses the latest Web technologies, including HTML5 canvas and WebSockets.

  • Rumpetroll

    A massively multiplayer experiment done in HTML5/Canvas/JavaScript and magical WebSockets. Rumpetroll is Norwegian, but probably not what you think.

  • Video Sync with WebSocket and Node

    A Node+WebSocket powered demo to sync videos across different browsers.

  • WordSquared

    A massively multiplayer online Scrabble-like word game.

  • HTML5 Web Socket in Essence
    HTML5 WebSocket defines a bi-directional, full-duplex communication channel operates through a single TCP connection, this article discusses its fantastic performance, the WebSocket protocol principle and its handshake mechanism, and develop a WebSocket application in action (Team Poker).

Real-time Gaming with Node.js + WebSocket on Google Cloud Platform

Demos
Echo Test
Demos on the Web
All About WebSocket
Benefits of WebSocket
Book About WebSocket
WebSocket API
WebSocket Protocol

References