# Quick and Simple Method for Building a WebSocket Server in Node.js

Imagine working on a document with colleagues simultaneously. You type a sentence, and it instantly appears on everyone else's screens, no refresh button is needed. This seamless collaboration is made possible by a powerful technology called WebSockets.

## **What are WebSockets?**

WebSockets are communication protocols that establish a persistent, two-way connection between a web browser (client) and a web server. Unlike HTTP, which operates on a request-response basis, WebSockets create an open channel for continuous data exchange in both directions – just like in our Google Docs example.

**Think of it like a constant conversation:**

* HTTP: Imagine having to raise your hand and wait for your turn to speak every time you want to communicate something in Google Docs. This is similar to HTTP, where the client makes a request, waits for the server's response, and then makes another request if needed.
    
* WebSockets: With WebSockets, it's like having a dedicated open line. You can speak (send data) and hear (receive data) simultaneously, fostering a real-time exchange.
    

WebSockets are great for building real-time functionality into web applications, such as games and chat apps, or for communicating financial trading data or IoT sensor data.

In this article, let’s create a WebSocket server, and use Postman to send and receive messages across the WebSocket connection.

## Setup the project

Create a new directory named `websockets`

```bash
mkdir websockets
```

Initialize the project using npm

```bash
npm init -y
```

Install the WebSocket library in the project

```bash
npm install ws --save
```

Create a file name `server.js` in the root directory

```javascript
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
    ws.on('message', function message(data) {
        console.log('received: %s', data);
    });

    ws.send('Hey!, Welcome to the websocket server!');
});
```

Run the server

```bash
node server.js
```

## Test the server

To test our WebSocket server we will be using Postman.

In Postman, select **New &gt; WebSocket Request** to open a new tab. Enter the WebSocket server URL. A WebSocket URL begins with `ws://` or `wss://` and our server is running on [`localhost:8080`](http://localhost:8080). Click **Connect**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713508462356/263a526c-9b13-48f5-9391-813a076cd42e.png align="center")

Once the connection between the server and the postman is established, the Message pane will display the list of incoming and outgoing network messages.

### Inspect handshake details.

The connection we established between the Postman client and the local server is bidirectional, which means that in addition to receiving messages, we can also send them. Under the **Message** tab, write your message and click **Send**.

We may check the outgoing message in the **Messages** pane.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713508953581/d84c1cef-b3f8-4e4b-ae4a-a09c53ce6252.png align="center")

### Verify the outgoing message was received by your local server:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713509029331/147c431c-fe6f-40ba-969d-51d41009ad5d.png align="center")

## **Send system information**

Let's update our WebSocket server and use it to send computer information in a set of interval

Let's install the system information package

```bash
npm install systeminformation
```

Let's add the function that will send a message about the current load on our CPU.

```javascript
import si from "systeminformation";

 setInterval(async () => {
    const cpuTemp = JSON.stringify(await si.currentLoad());
    ws.send(cpuTemp);
  }, 1000);
```

Here is the fully updated `server.js` file

```javascript
import { WebSocketServer } from 'ws';
import si from "systeminformation";

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
    ws.on('message', function message(data) {
        console.log('received: %s', data);
    });

    ws.send('Hey!, Welcome to the websocket server!');
    setInterval(async () => {
        const cpuTemp = JSON.stringify(await si.currentLoad());
        ws.send(cpuTemp);
    }, 1000);
});
```

Save your changes, and restart the local server from the command line:

```bash
node server.js
```

### Test the system information

Return to Postman and **Connect** to the local server. This time, we receive information about our CPU every second!

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713509474048/78051c88-de66-4f14-b741-c657f50bc949.png align="center")

We have explored the core concepts and walked through building a basic server that sends CPU load time to the client. It's just the beginning, we can leverage WebSockets to build applications that unleash the power of real-time communication like chat applications, real-time notifications etc.

Github source code - [https://github.com/icon-gaurav/node-websockets.git](https://github.com/icon-gaurav/node-websockets.git)
