DEV Community

Cover image for Quick introduction to WebSockets with Node.js
Bobby Iliev
Bobby Iliev

Posted on • Originally published at devdojo.com

Quick introduction to WebSockets with Node.js

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
Enter fullscreen mode Exit fullscreen mode

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");
    }
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}`);
    });
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You should see the following output:

hello world
hello world
hello world
...
Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
decker67 profile image
decker • Edited

Thank you for the starter. I put it into a github project and switched it to import/export ES6.

Collapse
 
bobbyiliev profile image
Bobby Iliev

That is great! Thank you!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good introduction thanks for sharing.

Collapse
 
eacolt profile image
Simon • Edited

Thank you so much , now I know what is websocket!