JavaScript - WebSockets & Streaming
Overview
Estimated time: 15–20 minutes
WebSockets enable real-time, two-way communication. Streaming APIs allow processing data as it arrives.
Learning Objectives
- Open and use a WebSocket connection.
- Work with streaming data in JavaScript.
Prerequisites
WebSockets
const ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = () => ws.send('Hello!');
ws.onmessage = e => console.log(e.data);
Streaming APIs
fetch('https://example.com/stream')
.then(response => response.body.getReader())
.then(reader => {/* ... */});
Common Pitfalls
- WebSockets require server support and may be blocked by firewalls.
Summary
WebSockets and streaming APIs are essential for real-time and large-data web applications.