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.