Websockets: Blazing Fast Data Exchange

WebSockets are a protocol for establishing long-lasting connections between several nodes. Once the connection is established via a handshake, all subsequent messages are sent immediately. Not needing to wait for request-response pairs, as in the HTML protocol, greatly increases transmission speed. The connection is full-duplex, meaning data can be received and send at the same time, in both directions. In summary, these capabilities allow real-time data exchange between several nodes. WebSockets are the foundation for video streaming, audio streaming and chat applications.

While working on a new application, I discovered WebSockets as a protocol and facilitator for instantaneous, constant data exchange. I also discovered a flexible, event-driven programming style that enables parts of a web-application to re-render itself whenever new data is received. This makes it great for highly interactive applications as well.

In this article, you will get a general overview about WebSockets and see how an example plain JavaScript application with client and server is setup using the socket.io framework.

This article originally appeared at my blog.

How WebSockets Work

WebSockets are based on the HTTP protocol. Either via port 80, or encrypted via port 443, client and server perform a handshake. This handshake has the form of an OPTIONS request from client to server. Here is an example of how the HTTP header look like.

The server then returns a connection upgrade response.

And then, the WebSocket connection between the client and server is created.

WebSocket messages are simple data: strings, structured, data, or binary. You can see the exchanged messages with a suitable browser, for example with the Firefox Developer Tools.

NodeJS Example

In this section I will show how to setup a client to server WebSocket connection using the [socket.io](https://socket.io/) library. The idea for this example is based on a great tutorial of Heroku: The server will send periodic time updates to the client, and the client renders the time information in a clock widget.

General Setup

First of all, create two folders client and server, and put an index.js file on each. Then, initialize an npm package in each project with npm init. Answer the raised questions as you like. Finally, use npm i socket.io express in each project. After these steps, your directory layout should look like this:

Implementing the Server

The server has two responsibilities: To accept incoming client connections, and to send time-information to all registered clients. The server itself will be written with Express.

In the file index.js, we start an express server instance.

Now we add socket.io to our server. In the above snipped, we created the backendServer object, an instance of HttpServer. Socket.io needs this object to bind its functions and add an endpoint to which clients can connect. We pass this object to the Socket.io constructor, together with an optional config object. Out of the box, socket.io does a great job autoconfiguring itself. If you need to customize the connection details, take a look at the official documentation.

Now, the server is ready, but does not provide any functionality yet. Let’s see how to setup the client.

Implementing the Client

The client follows similar steps as before.

First, we create an Express server instance and add socket.io. Additionally, we also deliver static HTML from the html directory.

Second, we add the socket.io JavaScript client to the HTML page that the express servers delivers.

And finally, we establish the connection to the backend server by adding — for simplicity — an inline script declaration to the index.html file.

Now, client and server are connected.

Exchanging Messages between Client and Server

Messages between client and server are based on events. There are two sources for events: lifecycle and custom events.

Lifecyle events concern the lifecyle of the connection. The first event connect establishes the connection. If for any reasons the connection is disrupted by a networking issue, then a connectError is created, followed by reconnects event to re-establish the connections. Finally, clients can explicitly disconnect. See also the full lifecycle diagram.

To let the server log a message upon being connected, you add the following code to the file server/index.js.

Custom events are designed by the application. An event needs a name, and optionally a payload that is transmitted. This event-name is used in two places: One node emits an event, and other nodes listen to this event.

Lets implement the periodic sending of the current server time to the client.

In server/index.js, set a 5 seconds interval to send the time.

And in the file client/html/index.html, add an event listener. Upon receiving the event, the defined callback function will be executed. In this example, the function will manipulate the DOM to show the server time, and it will also log the received server time to the console-

Exchange Server Time: Complete Source Code

Here is the complete source code for this example.







This article showed how to implement an example WebSocket application in which the server sends the current time to its connected clients. Setup and configuration of a WebSocket connection becomes very easy with using the socket.io library.

WebSocket’s are an interesting mechanism for a constant connection between server and client. This connection enables instantaneous, event driven data exchange for texts, structured data such as JSON, and even binary data. In JavaScript applications, combining CommonJS and Web APIs, especially the DOM API, you can design very interactive web pages. I was surprised how easy it is to have a basic single-page-applications in which different web page parts send and receive events to updates its DOM. I’m looking forward to use WebSockets more often in future applications.

IT Project Manager & Developer