Blog Post

Real-time Data Distribution Via Websocket and NodeJS

  • 4 mins read
by Will Newmarch
Senior Full-stack Developer

Published on Tuesday 29th July 2014

Two of my favourite technologies in the world of web development at the moment are NodeJS and WebSocket. NodeJS is creating new ways of thinking when coding server-side by allowing for quick and easy implementation of asynchronous, real-time environments. WebSocket is now being included in the latest browsers and allows for real-time two way communication. It turns out it’s very easy to implement WebSocket using NodeJS and the results are pretty awesome. After doing a bit of research into how other people have implemented the two, I decided to make my own chunk of code to distribute data to anyone else connected. This would allow me to set up a multitude of scenarios in next to no time, opening up some very exciting possibilities. I was impressed by the fact that in only 35 lines I could set up a server-side mechanism to distribute any data it receives to all other connections involved. Below is the code chunk and for this example, you must have installed NodeJS on your server as well as the ‘http’ package and the ‘websocket’ package. There are other WebSocket packages available, I just liked the way this one was implemented.
"use strict";
(function(){
	var connections = []; // list of current connections
	var http = require('http'); // http require
	var WebSocketServer = require('websocket').server; // websocket require
	var webSocketsServerPort = 1337; // choose a port number
	
	var httpServer = http.createServer(function(request, response) { /* We don't need to do anything here as we're creating a WebSocket server, not an HTTP server */ });
	httpServer.listen(webSocketsServerPort, function() {
		console.log((new Date()) + " :: The server is listening on port " + webSocketsServerPort);
	});
	
	var webSocketServer = new WebSocketServer({
		httpServer: httpServer // WebSocket server is tied to a HTTP server. WebSocket request is just an enhanced HTTP request.
	});
	 
	webSocketServer.on('request', function(request) { // This callback function is called every time someone tries to connect to the WebSocket server
		console.log((new Date()) + " :: Connection from origin " + request.origin + ".");
		var connection = request.accept(null, request.origin); 
		var index = connections.push(connection); // Add connection to list of current connections
	 
		// user sent some message
		connection.on('message', function(message) {
			for (var i=0; i < connections.length; i++) { // broadcast message to all current connections
				connections[i].sendUTF(message.utf8Data);
			}
		});
	 
		// user disconnected
		connection.on('close', function(connection) {
			console.log((new Date()) + " :: Peer " + connection.remoteAddress + " disconnected.");
			connections.splice(index, 1); // remove user from the list of live connections
		});
	});
})();
If you’re interested to see exactly what this code can do in just a couple of minutes, demo it by following these simple steps… Make sure you have NodeJS and the required packages (‘http’ and ‘websocket’) installed on your server. Next, upload the code into a JavaScript file onto your server and run with NodeJS. After setting this up you can create a WebSocket connection using just a few lines of JavaScript. This can even be achieved by pasting the code into a browser console* that supports WebSocket if you want to demo it quickly. Once set up, all other connections will receive anything sent to the server. *This must be done when the console is open on a non-secure site (http only) To connect to your data distribution code, firstly, create your WebSocket connection by running the below line, adding your server’s IP in the right part. This is creating a WebSocket object and connecting via the WebSocket protocol (ws) to your server IP and to the port set in the previous code.

var ws = new WebSocket("ws://[SERVER IP]:1337");
Next, we set up what to do when a message is received client-side. Here I’m console logging the object returned from the server, which will contain several pieces of data to do with the message as well as the message itself.

ws.onmessage = function(data){ console.log(data); }
Now our WebSocket is set up and we can send it something. Why not begin by greeting everyone else who’s connected? You will also receive this message as the code simply distributes everything it receives to every connection it is handling.

ws.send("Hello there!");

And there you have it. With 38 lines of code, we have created a data distribution mechanism, connected to it, and sent it some data!
WebSocket is gradually being rolled out in the latest browsers, and is constantly being utilised to help out with real-time applications. A good source to check up on their status can be found on Wikipedia – http://en.wikipedia.org/wiki/WebSocket#Browser_support