Lesson 54 of 55
javascriptWebSockets & Real‑time Communication
13 mins
Course progress98%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 54 of 55
javascript13 mins
Keep these ideas in mind as you work through the lesson.
WebSockets provide a full‑duplex channel between a browser and a server. Unlike HTTP, the connection stays open, allowing low‑latency push data.
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.
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.
<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>
EventSource) can be simpler.WebSockets empower truly interactive web apps while staying within the standard web platform.