WebSocket API:
1const ws = new WebSocket("wss://api.example.com/ws");23ws.onopen = () => {4 ws.send(JSON.stringify({ type: "subscribe", channel: "prices" }));5};67ws.onmessage = (event) => {8 const data = JSON.parse(event.data);9 updatePrices(data);10};1112ws.onerror = (error) => {13 console.error("WebSocket error:", error);14};1516ws.onclose = () => {17 // Implement reconnection18 setTimeout(connect, 3000);19};
Socket.io alternative:
1import { io } from "socket.io-client";23const socket = io("wss://api.example.com");4socket.on("priceUpdate", handlePriceUpdate);
Best practices: