DEV Community

Cover image for WebSocket : Create your First WebSocket connection
Nirvan Jha
Nirvan Jha

Posted on

WebSocket : Create your First WebSocket connection

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

  • 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.
  1. For leetcode (Leetcode is a problem solving website for programmers), whenever the user submits a problem, the following might happen -

Image description

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

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

  1. 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

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

Backend

Ws in Node.js (Code)

  1. Initialize an empty Node.js project
npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Add tsconfig to it
npx tsc --init
Enter fullscreen mode Exit fullscreen mode
  1. Update tsconfig
"rootDir": "./src",
"outDir": "./dist",
Enter fullscreen mode Exit fullscreen mode

3.1. Create a src folder and inside it create index.ts file.

  1. Install ws
npm i ws @types/ws
Enter fullscreen mode Exit fullscreen mode

If you want to use the standard http library: -

  1. 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');
});
Enter fullscreen mode Exit fullscreen mode

If you want to use Express Library:-

  1. Code using express 5.1. Install Express
npm install express @types/express
Enter fullscreen mode Exit fullscreen mode

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!!');
});
Enter fullscreen mode Exit fullscreen mode
  1. Open the terminal and write:-
tsc -b
Enter fullscreen mode Exit fullscreen mode
node dist/index.js
Enter fullscreen mode Exit fullscreen mode
  1. To check whether the websocket is established or not u can go to https://hoppscotch.io/realtime/websocket

Image description

Client side code

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

  1. Create a React project
npm create vite@latest
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

In Nextjs write this code in Page.tsx and make it client side by writing "use client" at the top of Page.tsx

  1. Open the terminal to run this project:-
npm run dev
Enter fullscreen mode Exit fullscreen mode

And now you are good to go.

Top comments (0)