WebSockets are a communication protocol in JavaScript that provide a full-duplex (two-way), persistent connection between the client (browser) and server over a single TCP connection.
✅ Key Features:
- 🔁 Real-time communication: Server can push data to the client anytime.
- 🔌 Persistent connection: Unlike HTTP, WebSocket stays open for continuous interaction.
- ⚡ Low latency: Faster than repeated HTTP requests (polling or long-polling).
- 🔄 Bi-directional: Both client and server can send and receive messages anytime.
✅ When to Use:
- Chat applications 💬
- Live sports scores or stock tickers 📈
- Multiplayer games 🎮
- Real-time dashboards or notifications 🔔
✅ Example in JavaScript:
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
socket.send('Hello Server!');
};
socket.onmessage = (event) => {
console.log('Received:', event.data);
};