WebSockets in Node.js 0.8.6 for Windows 7

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 the WebSocket-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.


42 thoughts on “WebSockets in Node.js 0.8.6 for Windows 7

  1. hi,
    thnx 4 d revised version but i still get the errors……
    C:\Program Files (x86)\nodejs>npm install websocket
    npm http GET https://registry.npmjs.org/websocket
    npm http 304 https://registry.npmjs.org/websocket
    npm WARN package.json websocket@1.0.6 No README.md file found!

    > websocket@1.0.6 install C:\Program Files (x86)\nodejs\node_modules\websocket
    > node-gyp rebuild

    C:\Program Files (x86)\nodejs\node_modules\websocket>node “C:\Program Files (x86
    )\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node
    -gyp.js” rebuild
    gyp ERR! configure error
    gyp ERR! stack Error: Can’t find Python executable “python”, you can set the PYT
    HON env variable.
    gyp ERR! stack at failNoPython (C:\Program Files (x86)\nodejs\node_modules\n
    pm\node_modules\node-gyp\lib\configure.js:110:14)
    gyp ERR! stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_module
    s\node-gyp\lib\configure.js:74:11
    gyp ERR! stack at Object.oncomplete (fs.js:297:15)
    gyp ERR! System Windows_NT 6.1.7600
    gyp ERR! command “node” “C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\nod
    e_modules\\node-gyp\\bin\\node-gyp.js” “rebuild”
    gyp ERR! cwd C:\Program Files (x86)\nodejs\node_modules\websocket
    gyp ERR! node -v v0.8.5
    gyp ERR! node-gyp -v v0.6.3
    gyp ERR! not ok
    npm ERR! websocket@1.0.6 install: `node-gyp rebuild`
    npm ERR! `cmd “/c” “node-gyp rebuild”` failed with 1
    npm ERR!
    npm ERR! Failed at the websocket@1.0.6 install script.
    npm ERR! This is most likely a problem with the websocket package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR! node-gyp rebuild
    npm ERR! You can get their info via:
    npm ERR! npm owner ls websocket
    npm ERR! There is likely additional logging output above.

    npm ERR! System Windows_NT 6.1.7600
    npm ERR! command “C:\\Program Files (x86)\\nodejs\\\\node.exe” “C:\\Program File
    s (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js” “install” “websocket”
    npm ERR! cwd C:\Program Files (x86)\nodejs
    npm ERR! node -v v0.8.5
    npm ERR! npm -v 1.1.46
    npm ERR! code ELIFECYCLE
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR! C:\Program Files (x86)\nodejs\npm-debug.log
    npm ERR! not ok code 0

    • From the looks of the error messages, it appears that you need to install Python. You will also need to install Visual C++. The links to both are provided in the post.

      • Python 2.7.3 Windows Installer (Windows binary — does not include source)
        Python 2.7.3 Windows X86-64 Installer (Windows AMD64 / Intel 64 / X86-64 binary [1] — does not include source)
        Python 2.7.3 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6 and 10.7 [2])
        Python 2.7.3 Mac OS X 32-bit i386/PPC Installer (for Mac OS X 10.3 through 10.6 [2])
        Python 2.7.3 compressed source tarball (for Linux, Unix or Mac OS X)
        Python 2.7.3 bzipped source tarball (for Linux, Unix or Mac OS X, more compressed)

        whch python i shud install

  2. sir,
    i have trying this websockets just as the way you explain it to me but when it comes to install the websockets using command prompt it always give me error like
    C:\Users\anando 9ohtaw>cd “c:\program files\nodejs”

    c:\Program Files\nodejs>npm install websocket
    npm http GET https://registry.npmjs.org/websocket
    npm http 304 https://registry.npmjs.org/websocket
    npm WARN package.json websocket@1.0.6 No README.md file found!
    npm ERR! Error: EPERM, mkdir ‘c:\Program Files\nodejs\node_modules\websocket’
    npm ERR! { [Error: EPERM, mkdir 'c:\Program Files\nodejs\node_modules\websocket
    ']
    npm ERR! errno: 50,
    npm ERR! code: ‘EPERM’,
    npm ERR! path: ‘c:\\Program Files\\nodejs\\node_modules\\websocket’,
    npm ERR! fstream_type: ‘Directory’,
    npm ERR! fstream_path: ‘c:\\Program Files\\nodejs\\node_modules\\websocket’,
    npm ERR! fstream_class: ‘DirWriter’,
    npm ERR! fstream_stack:
    npm ERR! [ 'DirWriter._create (c:\\Program Files\\nodejs\\node_modules\\npm\\
    node_modules\\fstream\\lib\\dir-writer.js:36:23)',
    npm ERR! 'c:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\mkdir
    p\\index.js:45:53',
    npm ERR! 'Object.oncomplete (fs.js:297:15)' ] }
    npm ERR!
    npm ERR! Please try running this command again as root/Administrator.

    npm ERR! System Windows_NT 6.1.7601
    npm ERR! command “c:\\Program Files\\nodejs\\\\node.exe” “c:\\Program Files\\nod
    ejs\\node_modules\\npm\\bin\\npm-cli.js” “install” “websocket”
    npm ERR! cwd c:\Program Files\nodejs
    npm ERR! node -v v0.8.6
    npm ERR! npm -v 1.1.48
    npm ERR! path c:\Program Files\nodejs\node_modules\websocket
    npm ERR! fstream_path c:\Program Files\nodejs\node_modules\websocket
    npm ERR! fstream_type Directory
    npm ERR! fstream_class DirWriter
    npm ERR! code EPERM
    npm ERR! errno 50
    npm ERR! stack Error: EPERM, mkdir ‘c:\Program Files\nodejs\node_modules\websock
    et’
    npm ERR! fstream_stack DirWriter._create (c:\Program Files\nodejs\node_modules\n
    pm\node_modules\fstream\lib\dir-writer.js:36:23)
    npm ERR! fstream_stack c:\Program Files\nodejs\node_modules\npm\node_modules\mkd
    irp\index.js:45:53
    npm ERR! fstream_stack Object.oncomplete (fs.js:297:15)
    npm ERR! Error: EPERM, open ‘c:\Program Files\nodejs\npm-debug.log’
    npm ERR! { [Error: EPERM, open 'c:\Program Files\nodejs\npm-debug.log']
    npm ERR! errno: 50,
    npm ERR! code: ‘EPERM’,
    npm ERR! path: ‘c:\\Program Files\\nodejs\\npm-debug.log’ }
    npm ERR!
    npm ERR! Please try running this command again as root/Administrator.

    npm ERR! System Windows_NT 6.1.7601
    npm ERR! command “c:\\Program Files\\nodejs\\\\node.exe” “c:\\Program Files\\nod
    ejs\\node_modules\\npm\\bin\\npm-cli.js” “install” “websocket”
    npm ERR! cwd c:\Program Files\nodejs
    npm ERR! node -v v0.8.6
    npm ERR! npm -v 1.1.48
    npm ERR! path c:\Program Files\nodejs\npm-debug.log
    npm ERR! code EPERM
    npm ERR! errno 50
    npm ERR! stack Error: EPERM, open ‘c:\Program Files\nodejs\npm-debug.log’
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR! c:\Program Files\nodejs\npm-debug.log
    npm ERR! not ok code 0

    c:\Program Files\nodejs>

    • You do not seem to have write permissions in the nodejs folder. You need the proper permissions to add things in this folder. Either give yourself permission, or contact the machine’s admin.

  3. Hi I am getting the following error even after installing visual c++ and python

    C:\Program Files\nodejs>npm install websocket
    npm http GET https://registry.npmjs.org/websocket
    npm http 304 https://registry.npmjs.org/websocket

    > websocket@1.0.7 install C:\Program Files\nodejs\node_modules\websocket
    > node install.js

    [websocket v1.0.7] Attempting to compile native extensions.
    [websocket v1.0.7]
    Native code compile failed!!
    On Windows, native extensions require Visual Studio and Python.
    On Unix, native extensions require Python, make and a C++ compiler.
    Start npm with –websocket:verbose to show compilation output (if any).
    websocket@1.0.7 node_modules\websocket

    Please can you help me in this regard
    Thanks in advance

    • I haven’t seen this error before. Are you using Windows 7 and version 0.8.6 of Node.js? Have you looked at the -websocket:verbose compiler output?

      • I am using windows xp(service pack 3). Is this the problem of OS?
        How do i check the verbose compiler output?

        • I’m not sure, but it certainly could be an OS issue. Are you using version 0.8.6 of Node.js and version 2.7 of Python? To view the compiler output, try:
          npm install websocket -websocket:verbose

          • Hi dude,
            Thanks for the help and finally i acheived it by uninstalling node.js and again installing it.
            One more thisng i want to know is I am able to send the text and get it back successfully. But How to achieve video conference, i mean how to send the stream using this websocket server. Thanks in advance.

          • I’m glad you were able to get it working. If you want to video conference, then you’ll probably need to use the getUserMedia specification. I wrote a short article on the topic over at SitePoint. At the time, only Opera 12 was supported, but I believe this has changed. You’ll also need to connect the video stream to the WebSocket. I suggest some Google searching for “getUserMedia and WebSockets”, as I’m sure people have already done this. Good luck!

  4. I am trying to create a websocket server using the ws module.
    i am using the function ws.createserver method for creating the server, as I discovered on all the sites but when i run the script, it is giving an error the createserver method doesn’t exist.
    I have been searching this on the net for the past 2 days but everywhere, they are using this method..
    PLEASE HELP !!

  5. I get the following verbose response – not sure what it means, but the compilation fails every time:

    C:\Program Files\nodejs>npm install websocket -websocket:verbose
    npm http GET https://registry.npmjs.org/websocket
    npm http 304 https://registry.npmjs.org/websocket

    > websocket@1.0.7 install C:\Program Files\nodejs\node_modules\websocket
    > node install.js

    [websocket v1.0.7] Attempting to compile native extensions.

    C:\Program Files\nodejs\node_modules\websocket>node “C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js” rebuild
    Building the projects in this solution one at a time. To enable parallel build, please add the “/m” switch.
    C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Platform.targets(42,5): error MSB8020: The builds tools for Visual Studio 2010 (Platform Toolset = ‘v100′) cannot be found. To build using the v100 build tools, either click the Project menu or right-click the solution, and then select “Update VC++ Projects…”. Install Visual Studio 2010 to build using the Visual Studio 2010 build tools. [C:\Program Files\nodejs\node_modules\websocket\build\validation.vcxproj]
    C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Platform.targets(42,5): error MSB8020: The builds tools for Visual Studio 2010 (Platform Toolset = ‘v100′) cannot be found. To build using the v100 build tools, either click the Project menu or right-click the solution, and then select “Update VC++ Projects…”. Install Visual Studio 2010 to build using the Visual Studio 2010 build tools. [C:\Program Files\nodejs\node_modules\websocket\build\xor.vcxproj]
    gyp[websocket v1.0.7]
    Native code compile failed!!
    On Windows, native extensions require Visual Studio and Python.
    On Unix, native extensions require Python, make and a C++ compiler.
    Start npm with –websocket:verbose to show compilation output (if any).
    websocket@1.0.7 node_modules\websocket

    • The error says that the Visual Studio build tools cannot be found. You need to install Python and Visual Studio in order to use the ws module.

      • Thanks for the prompt reply. Actually, I have installed both the Python 2.7.3 and Visual Studio Express 2012 for Windows Desktop (my OS is x64 W7), and this error appeared with these packages installed. What I already found out is that there were some x64 issues which have supposed to be solved in the WebSocket-Node version 1.0.7 (https://github.com/TooTallNate/node-gyp/issues/112) – still does not work for me. I’m testing the server without the native build support – it runs, but XOR and UTF-8 wouldb be eventually needed as well.

  6. Hello Thank for the tutorial, a lovely one!
    Everything works ok until My server tries to push information to the clients using a web browser: i looked in the firebug console and i keep getting the error after about 30 seconds “The connection to ws://127.0.0.1:8080/ was interrupted while the page was loading.”. But when i try creating and using the WebSocketClient via node, the clients on the command line interface receives the messages ok, but via the browser I get that message above. what could be going wrong? I thought it was a windows issue and tried with Ubuntu server, still the same error.

      • Hello, Thanks for the speedy reply, i already used that tutorial as well to test the browser based session, and that’s how i actually came upon this error. “The connection to ws://127.0.0.1:8080/ was interrupted while the page was loading.” what could be wrong?

        • Sorry, Chuka, I’m not sure what the problem could be. It’s also possible that it could be a versioning problem. The tutorial was verified with version 0.8.6 of Node.js, so it’s possible something could have changed since then.

  7. Hello,

    The server knows hear messages … But how can it send users? For example, we can bind WebSockets to a database and send the data to all users?

    Thank you in advance,
    Dev-Funky.

  8. Hello!
    First thanks very much for this excellent tutorial, gave me a clear view of Websocket with Node.js
    But unfortunaly I could not test this. I still have problems to install the websocket module.
    I install already Visual C++ Express and Phyton 2.7,
    I changed the permission in the folder C:\Program Files\nodejs,
    I tried to execute the command: npm install websocket -websocket:verbose but nothing happen.
    In this moment I don’t know what else I should do.
    Can you be so kind and help me PLEASE. Thanks,

    • What do you mean nothing is happening? Do you actually have Node.js/NPM installed? Also, this post is becoming a bit dated, so version compatibility issues could start becoming a problem.

      • Hello again :)
        Yes, I have the NPM installed. I’m using Window 7, could be this a problem for the correct installation of Websocket Module?
        I can not do nothing till I install this module. I’ll apprecite very much your help

          • Yes, if I execute this command: npm install websockket, this is the result of this command. As I said before, I have already Visual C++ and Phyton installed. Thanks very much for your help and your time

            npm http GET https://registry.npmjs.org/websocket
            npm http 304 https://registry.npmjs.org/websocket

            >websocket@1.0.7 install C:\Users\Me\node_modules\websocket
            > node install.js

            [websocket v1.0.7] Attempting to compile native extensions.
            [websocket v1.0.7]
            Native code compile failed!!
            On Windows, native extensions require Visual Studio and Python.
            On Unix, native extensions require Python, make and a C++ compiler.
            Start npm with –websocket:verbose to show compilation output (if any).
            websocket@1.0.7 node_modules\websocket

          • The problem seems to be that npm cannot find Visual Studio and/or Python. You say that you have installed them already, but there’s a chance that they aren’t in your PATH.

  9. C:\Program Files\nodejs>npm install
    npm ERR! install Couldn’t read dependencies
    npm ERR! Error: ENOENT, open ‘C:\Program Files\nodejs\p
    npm ERR! If you need help, you may report this log at:
    npm ERR!
    npm ERR! or email it to:
    npm ERR!

    npm ERR! System Windows_NT 6.1.7601
    npm ERR! command “C:\\Program Files\\nodejs\\\\node.exe
    ejs\\node_modules\\npm\\bin\\npm-cli.js” “install”
    npm ERR! cwd C:\Program Files\nodejs
    npm ERR! node -v v0.8.16
    npm ERR! npm -v 1.1.69
    npm ERR! path C:\Program Files\nodejs\package.json
    npm ERR! code ENOENT
    npm ERR! errno 34
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR! C:\Program Files\nodejs\npm-debug.log
    npm ERR! not ok code 0

    Im getting this error kindly help

    • It looks like you only typed npm install. You need to either have a package.json file, or specify the package name from the command line as shown in the tutorial.