Monthly Archives: November 2014

Simple WebSocket & NodeJS Server Example

I’ve been searching for a NodeJS server for web sockets, but, required both the client and server to be run from within node. I wanted to connect to this server via a normal web page using WebSockets from HTML5. Here’s some code, hope you find it useful:

Server Code

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 3000});

wss.on('connection', function (ws) {
    ws.on('message', function (message) {
        console.log('received: %s', message);
        ws.send(message + "!!!!");

Client Code

    var websocket = new WebSocket('ws://localhost:3000');
    websocket.onopen = function (evt) {
        websocket.send("This Rocks!");
    websocket.onmessage = function (evt) {
        console.log('RESPONSE: ' +;