Barebone WebSocket with Node and Browser Console

I've been working with WebSocket for some of my projects in the past. WebSocket is a technology that allow us to have realtime interaction within a platform. Here I will write about basics of WebSocket and barebone setup to try this technology.

In general I'll write about:

  1. Realtime functionality requirement
  2. What is WebSocket technology
  3. Setting up WebSocket server on Node.js
  4. Simple scripts in the browser console to interact with the server in realtime

Realtime functionality requirement

Think about WhatsApp chat, Telegram chat, or Facebook Notifications. These are features that require realtime interactions where the users of the application expect to send/receive information without delay. There are a few ways we can achieve this.

  1. Long polling

    The client ask if there is any new updates to the server. This can be in periodic intervals. Here the client need to handle when to ask for an updates to the server.

  2. Server sent events (MDN link)

    Server sent new informations to the client. However the client can't send information to the server (one way communication).

  3. WebSocket

    This technology will allow client and server send and receive information (bi-directional).

On some cases we might choose one solution to another. For example when we need notifications for new update it might be better to do server sent events rather than wiring up WebSocket as the client doesn't need to send information to the server.

What is WebSocket technology

WebSocket is a techology that allows client and server to send and receive informations through events. These events are fired-up on client side and the server side. The client and server then can handle these events in realtime.

WebSocket connection is initiated with GET 1.1 UPGRADE request from the client side, when the WebSocket server accept the request the it will give 101 Switching Protocols response. After these handshakes that the client and WebSocket server can send and receive data in realtime.

Client and WebSocket Server

(MDN Reference for WebSocket)

Setting up WebSocket server on Node.js

Here I'll use node and websocket package to wire-up WebSocket server.

  1. Create a project folder

    mkdir websocket-server
  2. Initialize node project

    npm init -y
  3. Install websocket package

    npm install websocket
  4. Create the index file

    touch index.js
  5. Edit the index.js file and create basic webserver

    const http = require('http');
    
    const httpServer = http.createServer((req, res) => {
      console.log('we have received a request');
    });
    
    httpServer.listen(8080, () =>
      console.log('Server is listening to http://localhost:8080')
    );

    This will create a basic server that we can run using this command:

    node index.js

    When we try to open http://localhost:8080 in the browser, the script will log we have received a request in the command line.

  6. Next lets add websocket server in the index.js

    const http = require('http');
    const WebSocketServer = require('websocket').server;
    
    const httpServer = http.createServer((req, res) => {
      console.log('we have received a request');
    });
    
    httpServer.listen(8080, () => console.log('Server is listening to 8080'));
    
    const websocket = new WebSocketServer({
      httpServer: httpServer,
    });

    These will initialize the WebSocket for us using the websocket package and wire-it up to our http server

  7. Next we'll need to add the WebSocket events handling

    const http = require('http');
    const WebSocketServer = require('websocket').server;
    
    const httpServer = http.createServer((req, res) => {
      console.log('we have received a request');
    });
    
    httpServer.listen(8080, () => console.log('Server is listening to 8080'));
    
    const websocket = new WebSocketServer({
      httpServer: httpServer,
    });
    
    let connection = null;
    
    websocket.on('request', (request) => {
      connection = request.accept(null, request.origin);
      connection.on('close', () => console.log('WebSocket is Closed!'));
    
      connection.on('message', (message) => {
        console.log(`Received message: ${message.utf8Data}`);
      });
    });

    These will handle the WebSocket events that we receive from client.

  8. To show how the server send the information in realtime lets add a function that trigger periodically to the client.

    const http = require('http');
    const WebSocketServer = require('websocket').server;
    
    const httpServer = http.createServer((req, res) => {
      console.log('we have received a request');
    });
    
    httpServer.listen(8080, () => console.log('Server is listening to 8080'));
    
    const websocket = new WebSocketServer({
      httpServer: httpServer,
    });
    
    let connection = null;
    
    websocket.on('request', (request) => {
      connection = request.accept(null, request.origin);
      connection.on('close', () => console.log('WebSocket is Closed!'));
    
      connection.on('message', (message) => {
        console.log(`Received message: ${message.utf8Data}`);
      });
    
      serverSendMessage();
    });
    
    const serverSendMessage = () => {
      connection.send(`Server send message at ${new Date().toISOString()}`);
    
      setTimeout(serverSendMessage, 5000);
    };

    These will send a message with the date every 5 seconds to the client after the WebSocket connection is established.

Simple script in the browser console to interact with WebSocket server in realtime

To try the WebSocket on the client side we can use browser console DevTools directly without writing any extra html stuff. So this will be pure JavaScript codes using API that are already build-in within the browser.

  1. Don't forget to run the WebSocket server in command line:

    node index.js
  2. Open your browser and the DevTools (for Chrome based browser usually we can open by pressing F12 key)

  3. Then write this in the console:

    let ws = new WebSocket('http://localhost:8080');

    This will initialize the WebSocket on the client side

  4. Next lets log the messages that are sent by the Server

    ws.onmessage = (message) => console.log(`Server: ${message.data}`);

    This will add an event listener to the onmessage, so everytime there is a new message from the server we will log it.

  5. Next lets try sending a message from the client

    ws.send('Hello server, this is from client');

    You will see the message in the command line. Now we have barebone realtime interactions between client and WebSocket server. You can play with this and send modified texts to the WebSocket server.

  6. To end the connections execute this on the browser console:

    ws.close();

Summary

This write-up shows you how to code barebone WebSocket server and interact with it from client side with browser console. Obviously this is not production ready codes. These shows the basics of WebSocket interactions. We'll need to handle a lot more cases when we really want to implement realtime interactions with WebSocket.

For me personally I'd work with library such as Socket.io if I want to implement realtime feature because there are a lot of cases that are covered by the library already. Hopefully this post help you learn something new. Thanks for reading.