NOTE: This is an update of my previous post on configuring WebSockets on a Windows 7 installation of Node.js.
One of the lesser known features of HTML5 are WebSockets. This is mainly due to a lack of browser support and standardization. Still, there is a considerable amount of information available on the WebSockets API. However, in order to create a WebSockets program, a corresponding server is required. Unfortunately, the process of creating a WebSockets server is not as well documented, and therefore acts as another hurdle towards widespread adoption.
This post provides step-by-step instructions for creating a simple WebSockets echo server. The server allows developers to test client code by echoing back any requests that it receives. The server is implemented in the Node.js framework, which can be run on a developer’s local machine, eliminating the need for additional hardware.
Node.js, written in C++ and JavaScript, allows users to rapidly create web applications. It is well known for creating web servers using server-side JavaScript. This post is based on version 0.8.6 of Node.js running on Windows 7. I expect that the steps outlined below should be somewhat similar for other versions and operating systems. This is not intended to be a Node.js tutorial, but rather a guide to rapidly creating a WebSockets server.
Installing Node.js
The first step is to install Node.js on your local machine. Node.js can be downloaded from the project’s homepage. Download a prebuilt version of Node.js by selecting the Windows Installer option. Next, run the installer and locate the resulting Node.js installation directory. On my machine, the installer configured Node.js in the “C:\Program Files (x86)\nodejs” directory. If necessary, change the permissions of the ‘nodejs’ directory so that you can create/modify files.
Installing the WebSockets Protocol
The Node.js framework does not include native support for WebSockets, which means that a third party solution is required. There are a number of WebSockets implementations available for Node.js, but this tutorial focuses specifically on theWebSocket-Node project. WebSocket-Node can be easily configured using the Node Package Manager, or npm, which comes with Node.js. To install WebSocket-Node, open a command line window and type the following commands:
cd "C:\Program Files (x86)\nodejs" npm install websocket
Starting with version 1.0.6 of WebSocket-Node, Windows users are also required to also install Microsoft Visual C++ and Python 2.7 (NOT Python 3.x).
Creating the WebSockets Server
The Node.js framework executes standalone JavaScript files. In the ‘nodejs’ folder, create a file named ‘ws_server.js’ — this file will implement the echo server. The following code is taken directly from the WebSocket-Node GitHub page. Copy it into the ‘ws_server.js’ file.
#!/usr/bin/env node var WebSocketServer = require(‘websocket‘).server; var http = require(‘http‘); var server = http.createServer(function(request, response) { console.log((new Date()) + ‘ Received request for ‘ + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ‘ Server is listening on port 8080‘); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection‘s origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on(‘request‘, function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ‘ Connection from origin ‘ + request.origin + ‘ rejected.‘); return; } var connection = request.accept(‘echo-protocol‘, request.origin); console.log((new Date()) + ‘ Connection accepted.‘); connection.on(‘message‘, function(message) { if (message.type === ‘utf8‘) { console.log(‘Received Message: ‘ + message.utf8Data); connection.sendUTF(message.utf8Data); } else if (message.type === ‘binary‘) { console.log(‘Received Binary Message of ‘ + message.binaryData.length + ‘ bytes‘); connection.sendBytes(message.binaryData); } }); connection.on(‘close‘, function(reasonCode, description) { console.log((new Date()) + ‘ Peer ‘ + connection.remoteAddress + ‘ disconnected.‘); }); });
Running the WebSockets Server
To start the server, type the following command:
node ws_server.js
If everything works properly, the server will display a message that it is listening on port 8080. The next step is to test the server using a client application. The corresponding WebSockets client is covered in this post.