0% found this document useful (0 votes)
6 views1 page

Socket Notes For Frontend

Uploaded by

Parth Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Socket Notes For Frontend

Uploaded by

Parth Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

How Sockets Work (Frontend)

1. What is a Client Socket?


On the frontend, sockets allow browsers or apps to establish a persistent connection to the backend
server. This enables real-time communication without constant HTTP requests.

2. How Frontend Sockets Work


- The client creates a socket connection to the server. - Once connected, the client listens for
messages from the server. - The client can also emit (send) messages to the server.

3. Example (React + Socket.IO)


```jsx import { useEffect, useState } from 'react'; import { io } from 'socket.io-client'; const socket =
io('http://localhost:3000'); export default function Chat() { const [messages, setMessages] =
useState([]); const [input, setInput] = useState(''); useEffect(() => { socket.on('message', (msg) => {
setMessages((prev) => [...prev, msg]); }); }, []); const sendMessage = () => { socket.emit('message',
input); setInput(''); }; return ( {messages.map((msg, i) => {msg})} setInput(e.target.value)} /> Send );
} ```

4. Key Points
- Client sockets connect to the backend server. - They send and receive messages in real-time. -
Used in chat apps, notifications, and live dashboards.

You might also like