Quick introduction to WebSockets with Node.js

Quick introduction to WebSockets with Node.js

Written by Bobby Iliev on Jul 23rd, 2022 Views Report Post

Introduction

WebSockets allow you to send and receive data over a network without having to use a traditional HTTP protocol. Using WebSockets, you can build a real-time application. For example, you can send messages to other users without having to refresh the page to see the new messages.

We will be using the ws library. It is a Node.js module that allows you to create WebSockets servers and clients.

Prerequisites

Before you get started, make sure you have Node.js installed:

Setup

In order to install the ws library you need to run the following command:

npm install ws

Next, create a new file called server.js and open it in your favorite text editor.

Creating a WebSocket server

In the server.js file, create the following code:

const WebSocket = require('ws')

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

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});

Rundown of the code:

  • const WebSocket = require('ws'): Import the the ws module.
  • const wss = new WebSocket.Server({ port: 8081 }): Create a new WebSocket server on port 8081.
  • wss.on('connection', function connection(ws) {: When a new client connects to the server, the connection event is emitted.
  • const interval = setInterval(() => {: Create a new interval that sends a message to the client every second.
  • ws.send('hello world'): Send a message to the client.
  • ws.on("close", () => {: When the client disconnects, the close event is emitted.
  • ws.onerror = function () {: When an error occurs, the onerror event is emitted.

That way we will simulate a streaming application where the server sends a message to the client every second.

Then to start the server, run the following command:

node server.js

Next, leave the server running and open a new terminal window where we will prepare our client.

Creating a WebSocket client

In a new file called client.js file, add the following code:

const WebSocket = require('ws')
const ws = new WebSocket('ws://localhost:8081')
ws.on('open', function open() {
    ws.on('message', function message(data) {
      console.log(`${data}`);
    });
});

The above code creates a new WebSocket client and connects to the server on port 8081.

When a message is received from the server, the message event is emitted.

To test the client, run the following command:

node client.js

You should see the following output:

hello world
hello world
hello world
...

Example:

node ws example gif

Conclusion

This is a simple example of how to use WebSockets with Node.js.

If you want to learn more about WebSockets, check out the official documentation.

If you want to see how WebSockets work with Laravel, check out the following tutorial:

Laravel WebSockets

For further reading, I could also suggest taking a look at the following tutorial on what the difference between SSE and WebSockets is:

SSE vs WebSockets

Comments (0)