7/8/24, 11:31 PM DailyCode
What is backend communication?
In the real world, you have various backend systems, not just one.
For example, for a website like PayTM, whenever you do a transaction, the following might
happen
[Link] 1/12
7/8/24, 11:31 PM DailyCode
For leetcode, whenever the user submits a problem, the following might happen -
[Link] 2/12
7/8/24, 11:31 PM DailyCode
Types of communication
Synchronous (Strong coupling)
1. HTTP (REST/GraphQL)
2. Websocket (debatable if sync or async)
Asynchronous (Weak coupling)
1. Messaging queues
2. Pub subs
3. Server-Sent Events
4. Websocket (debatable if sync or async)
[Link] 3/12
7/8/24, 11:31 PM DailyCode
Websockets
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.
Use Cases for WebSockets:
Real-Time Applications: Chat applications, live sports updates, real-time gaming, and any
application requiring instant updates can benefit from WebSockets.
Live Feeds: Financial tickers, news feeds, and social media updates are examples where
WebSockets can be used to push live data to users.
Interactive Services: Collaborative editing tools, live customer support chat, and interactive
webinars can use WebSockets to enhance user interactio
Good example - [Link]
Why not use HTTP/REST? Why do you need ws?
[Link] 4/12
7/8/24, 11:31 PM DailyCode
1. Network Handshake happens for every request
2. No way to push server side events (You can use polling but not the best approach)
💡 Leetcode uses polling when you submit a problem
Websockets in [Link]
[Link] 5/12
7/8/24, 11:31 PM DailyCode
There are various libraries that let you create a ws server (similar to how express lets you create
an HTTP server)
1. [Link]
2. [Link]
3. [Link]
We’ll be using the ws library today.
💡 Problems with [Link] -
Even though [Link] is great (it gives you constructs like rooms to make the API much
cleaner), it’s harder to support multiple platforms in it (Android, IOS, Rust)
There are implementations in most platforms but not very up to date
[Link]
[Link]
Ws in [Link] (Code)
[Link] 6/12
7/8/24, 11:31 PM DailyCode
Initialize an empty [Link] project
npm init -y Copy
Add tsconfig to it
npx tsc --init Copy
Update tsconfig
"rootDir": "./src", Copy
"outDir": "./dist",
Install ws
npm i ws @types/ws Copy
Code using http library
import WebSocket, { WebSocketServer } from 'ws'; Copy
import http from 'http';
const server = [Link](function(request: any, response: any) {
[Link]((new Date()) + ' Received request for ' + [Link]);
[Link]("hi there");
});
const wss = new WebSocketServer({ server });
[Link]('connection', function connection(ws) {
[Link]('error', [Link]);
[Link]('message', function message(data, isBinary) {
[Link](function each(client) {
if ([Link] === [Link]) {
[Link](data, { binary: isBinary });
}
});
});
[Link] 7/12
7/8/24, 11:31 PM DailyCode
[Link]('Hello! Message From Server!!');
});
[Link](8080, function() {
[Link]((new Date()) + ' Server is listening on port 8080');
});
Code using express
npm install express @types/express Copy
import express from 'express' Copy
import { WebSocketServer } from 'ws'
const app = express()
const httpServer = [Link](8080)
const wss = new WebSocketServer({ server: httpServer });
[Link]('connection', function connection(ws) {
[Link]('error', [Link]);
[Link]('message', function message(data, isBinary) {
[Link](function each(client) {
if ([Link] === [Link]) {
[Link](data, { binary: isBinary });
}
});
});
[Link]('Hello! Message From Server!!');
});
[Link] 8/12
7/8/24, 11:31 PM DailyCode
Client side code
Websocket is a browser API that you can access (very similar to fetch)
Will work in a raw project , React project and Next project (needs to be client side)
Create a React project
npm create vite@latest Copy
Create a websocket connection to the server
import { useEffect, useState } from 'react' Copy
import './[Link]'
function App() {
const [socket, setSocket] = useState<WebSocket | null>(null);
useEffect(() => {
const newSocket = new WebSocket('[Link]
[Link] = () => {
[Link]('Connection established');
[Link]('Hello Server!');
}
[Link] = (message) => {
[Link]('Message received:', [Link]);
}
setSocket(newSocket);
return () => [Link]();
}, [])
return (
<>
hi there
</>
)
}
export default App
💡 Can you convert it to a custom hook called useSocket ?
[Link] 9/12
7/8/24, 11:31 PM DailyCode
[Link]
Create a fresh next project
Update [Link] to be a client component
Add the code to create a socket connection
"use client" Copy
import { useEffect, useState } from 'react'
export default function() {
const [socket, setSocket] = useState<WebSocket | null>(null);
useEffect(() => {
const newSocket = new WebSocket('[Link]
[Link] = () => {
[Link]('Connection established');
[Link]('Hello Server!');
}
[Link] = (message) => {
[Link]('Message received:', [Link]);
}
setSocket(newSocket);
return () => [Link]();
}, [])
return (
<>
hi there
</>
)
}
[Link] 10/12
7/8/24, 11:31 PM DailyCode
Scaling ws servers
In the real world, you’d want more than one websocket servers (Especially as your website gets
more traffic)
The way to scale websocket servers usually happens by creating a ws fleet
There is usually a central layer behind it that orchestrates messages
ws servers are kept stateless
[Link] 11/12
7/8/24, 11:31 PM DailyCode
[Link] 12/12