WebSocket : Create your First WebSocket connection
Tags: webdev, javascript, beginners, tutorial
Published: 2024-06-26 15:32:14

**What is Backend Communication?**
When One Backend system interacts with other Backend systems, Its called backend communication. In real world, there are various backend systems not just one. Lets see some examples:- 

1. For example, for a website like PayTM, whenever you do a transaction, the following might happen

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20p7hsgb7l2ag3l905fv.png)
* The **Backend1** will be doing the Money Transfer work and will delegate the task of sending notification of money transfer via email, messaging to other backends. 

2. For leetcode (Leetcode is a problem solving website for programmers), whenever the user submits a problem, the following might happen - 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d2fgelrd4mamh4p3ukg.png)

**Types of communication:**
1. Synchronous (Strong coupling):-
  1. HTTP (REST/GraphQL)
 
2. Asynchronous (Weak coupling):-
  1. Messaging queues
  2. Pub subs
  3. Server-Sent Events 

3. WebSockets
  WebSockets are still debatable whether they are sync or async.

So what is Synchronous:- 
HTTP is considered synchronous due to its request-response model. In this model, a client sends a request to a server and waits for a response. The client sends a request, waits for a response, and only after receiving the response can it send another request.

Asynchronous:- 
It refers to a model where the client does not wait for the server to respond before proceeding with other tasks. Instead, the client can send multiple requests, and handle responses as they arrive. For Example:- 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4nfuhmiuaxvwqrofce6.png)

## Websockets
Websockets are a way of communication between the client(typically a web browser) and the server.
So why are we using websockets and why not HTTP??
 1. In HTTP, network Handshake happens for every request. Here the server 
 makes a request and waits for the response and when it recieves the 
 response, the connection gets closed. Now to make another request the 
 network handshake happens again. See below:- 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l47iu2ivanwt20cagesd.png)

 2. No way to push server side events. In an Http connection you can not 
 send events or requests (You can not do fetch("URL") from the server 
 side) from the server to the client. Only the Client can make requests. 
 (You can use polling but not the best approach).

**WebSockets provide a way to establish a persistent, full-duplex communication channel over a single TCP connection between the client (typically a web browser) and the server and solves the above two problems.**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9d89wwuvy0oulua72dt.png)

**Use Cases for WebSockets:**
1. Real-Time Applications: Chat applications, live sports updates, real-time gaming, and any application requiring instant updates can benefit from WebSockets.
2. Live Feeds: Financial tickers, news feeds, and social media updates are examples where WebSockets can be used to push live data to users.
3. Interactive Services: Chat application, Collaborative editing tools, live customer support chat, and interactive webinars can use WebSockets to enhance user interaction.

**Websockets in Node.js**
There are various libraries that let you create a ws server:-
https://www.npmjs.com/package/websocket
https://github.com/websockets/ws
https://socket.io/
 
We’ll be using the ws library today. Lets dive into code:- 

## <u>Backend</u>
**Ws in Node.js (Code)**
1. Initialize an empty Node.js project

```
npm init -y
```
2. Add tsconfig to it

```
npx tsc --init
```
3. Update tsconfig

```
"rootDir": "./src",
"outDir": "./dist",
```
3.1. Create a src folder and inside it create index.ts file. 

4. Install ws

```
npm i ws @types/ws
```
If you want to use the standard http library: - 
5. Code using http library

```
import WebSocket, { WebSocketServer } from 'ws';
import http from 'http';

const server = http.createServer(function(request: any, response: any) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.end("hi there");
});

const wss = new WebSocketServer({ server });

wss.on('connection', function connection(ws) {
  ws.on('error', console.error);

  ws.on('message', function message(data, isBinary) {
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data, { binary: isBinary });
      }
    });
  });

  ws.send('Hello! Message From Server!!');
});

server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});
```
If you want to use Express Library:-
5. Code using express
5.1. Install Express

```
npm install express @types/express
```
5.2. Writw this code in index.ts

```
import express from 'express'
import { WebSocketServer } from 'ws'

const app = express()
const httpServer = app.listen(8080)

const wss = new WebSocketServer({ server: httpServer });

wss.on('connection', function connection(ws) {
  ws.on('error', console.error);

  ws.on('message', function message(data, isBinary) {
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data, { binary: isBinary });
      }
    });
  });

  ws.send('Hello! Message From Server!!');
});
```
6. Open the terminal and write:- 

```
tsc -b
```

```
node dist/index.js
```
7. To check whether the websocket is established or not u can go to 
https://hoppscotch.io/realtime/websocket


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wje6yw4u6xfzdu2kr1hw.png)

## <u>Client side code</u>

> Websocket  is a browser API that you can access (very similar to fetch).

1. Create a React project

```
npm create vite@latest
```
2. Create a websocket connection to the server in App.tsx

```
import { useEffect, useState } from 'react'
import './App.css'

function App() {
  const [socket, setSocket] = useState<WebSocket | null>(null);

  useEffect(() => {
    const newSocket = new WebSocket('ws://localhost:8080');
    newSocket.onopen = () => {
      console.log('Connection established');
      newSocket.send('Hello Server!');
    }
    newSocket.onmessage = (message) => {
      console.log('Message received:', message.data);
    }
    setSocket(newSocket);
    return () => newSocket.close();
  }, [])

//Here you can write the code to maka chat application by adding a input box, by creating a state and the storing the message in it and rendering the messages on the screen. 
  return (
    <>
      hi there
    </>
  )
}

export default App
```

> In Nextjs write this code in Page.tsx and make it client side by writing "use client" at the top of Page.tsx
3. Open the terminal to run this project:- 

```
npm run dev
```
And now you are good to go.