WebSocket Basics : Hello World

In this article, you will learn the basics of WebSocket using NodeJS. We will write a very simple Hello WebSocket program. The reason we are not using Rails 5 is because we want to learn the concepts first. According to Mozilla Developer Network:

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Create the index.html file, this will be the WebSocket client that sends data to the WebSocket server.

<!DOCTYPE html>
<html lang="en">
<title>WebSocket Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        var ws = new WebSocket("ws://localhost:8080");
        ws.onopen = function(e) {
          console.log('Connected to server');

        function sendMessage() {
<body lang="en">

  <form id="echo_form" onsubmit="sendMessage(); return false;">
    <input class="form-control" type="text" name="message" id="message" placeholder="Type text to echo in here" value="" autofocus/>

    <button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">Send</button>


We need to install NodeJS. I had old version of node on my machine.

node -v

You can use brew to install node.

$ brew install node

This failed. I installed using NodeJS Mac installer. This installed node 6.9.4.

node -v

Next, we need to install WebSocker server. We can install the ws library for our Node.js application. According to the Node package manager website:

ws is a simple to use WebSocket implementation, up-to-date against RFC-6455, and probably the fastest WebSocket library for node.js.

We can install it by:

npm install ws

This gave an error:

enoent ENOENT: no such file or directory, open package.json

Create package.json file by running:

$ npm init 

This will prompt you to answer questions and create package.json. This will loook something like this:

  "name": "wstutorial",
  "version": "1.0.0",
  "description": "WebSocket Basics",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [
  "author": "Bala Paranj",
  "license": "MIT"

Let's now install the ws WebSocket library.

npm install ws
wstutorial@1.0.0 /Users/bparanj/temp/websocket
└─┬ ws@1.1.1 
  ├── options@0.0.6 
  └── ultron@1.0.2 

npm WARN wstutorial@1.0.0 No repository field.

Create server.js file with:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws){
  console.log('client connected');
  ws.on('message', function incoming(message){
    console.log('received: %s', message);

This creates a websocket server running on port 8080. We have two functions, one on connection, the other when the server receives the message from the client. In a terminal, run it:

node server.js

Open the index.html in the browser and enter 'hello world'. You will see the output in the terminal where the node server is running. Inspect Tab, select localhost, headers and see the different sections. If you make any changes to server.js, you have to restart the server. In this article, you learned how the client send data to the server. In the next article, we will see how the data sent by the server can be received by the client. You can download the source for this article from my github repo websocket.

Related Articles

Watch this Article as Screencast

You can watch this as a screencast WebSocket Basics : Hello World

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.