Quick introduction to WebSockets with Node.js
Tags: javascript, node, webdev, beginners
Published: 2022-08-28 09:32:16

## 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:

- [Download Node.js](https://nodejs.org/en/download/)

## Setup

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

```bash
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:

```js
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:

```bash
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:

```js
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:

```bash
node client.js
```

You should see the following output:

```bash
hello world
hello world
hello world
...
```

Example:

![node ws example gif](https://user-images.githubusercontent.com/21223421/180609383-2ba61adc-f95d-4545-b31f-9cba81f4a3e4.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](https://github.com/websockets/ws).

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

[Laravel WebSockets](https://devdojo.com/bobbyiliev/how-to-use-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](https://devdojo.com/bobbyiliev/how-to-create-a-simple-event-streaming-in-laravel#sse-vs-websockets)