Intermediate LevelHTML & Semantic Web
How do you initialize and manage WebSocket client connections in HTML/JS?
❓ Interview Prompt: Explain WebSocket client setup (ws:// and wss:// protocols), connection lifecycle events (onopen, onmessage, onerror, onclose), and full-duplex communication.
The WebSocket API provides full-duplex, bidirectional communication between browser clients and servers over a single persistent TCP connection.
Lifecycle Events:
•
'ws = new WebSocket("wss://...")': Establishes secure WebSocket connection.
•
'ws.onopen': Connection established.
•
'ws.onmessage': Incoming message from server.
•
'ws.send(data)': Transmits client payload to server.
Code Implementation Example
javascript
const socket = new WebSocket('wss://api.example.com/realtime');
socket.onopen = () => socket.send(JSON.stringify({ action: 'subscribe' }));
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Realtime update:', message);
};💡Initializing client WebSocket connection and listening for real-time messages.
🎯 Interview Key Takeaway
Use wss:// (WebSocket Secure) for bidirectional, full-duplex real-time communication between browser and server.
#WebSocket#wss://#Real-Time#Intermediate
Back to all HTML & Semantic Web Questions→