Lesson 54 of 55 · javascript
WebSockets & Real‑time Communication
Duration: 13 mins
WebSockets & Real‑time Communication
WebSockets provide a full‑duplex channel between a browser and a server. Unlike HTTP, the connection stays open, allowing low‑latency push data.
1️⃣ Browser API
const socket = new WebSocket('wss://echo.websocket.org');
socket.addEventListener('open', () => {
console.log('Connected');
socket.send('Hello server');
});
socket.addEventListener('message', e => {
console.log('Received:', e.data);
});
socket.addEventListener('close', () => console.log('Disconnected'));
send transmits a string or binary; message events fire on incoming data.
2️⃣ Node server (ws library)
npm install ws
// server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', msg => {
console.log('Client says:', msg);
ws.send(`Echo: ${msg}`);
});
});
Run with node server.js; clients can now connect to ws://localhost:8080.
3️⃣ Simple chat example (client side)
<div id="chat"></div>
<input id="msg" placeholder="Type a message" />
<button id="send">Send</button>
<script>
const ws = new WebSocket('ws://localhost:8080');
const chat = document.getElementById('chat');
const input = document.getElementById('msg');
document.getElementById('send').onclick = () => {
ws.send(input.value);
input.value = '';
};
ws.onmessage = e => {
const p = document.createElement('p');
p.textContent = e.data;
chat.appendChild(p);
};
</script>
4️⃣ When to use WebSockets?
- Live chat, collaborative editors, real‑time dashboards.
- For occasional server‑push, Server‑Sent Events (
EventSource) can be simpler. - Remember to handle reconnection, heartbeats, and graceful closure.
WebSockets empower truly interactive web apps while staying within the standard web platform.