WebSocket pool — manage multiple WebSocket connections.
1const WebSocket = require("ws");23class WebSocketPool {4 constructor(urls, options = {}) {5 this.urls = urls;6 this.maxSize = options.maxSize || urls.length;7 this.connections = [];8 this.available = [];9 this.currentIndex = 0;10 }1112 async connect() {13 for (const url of this.urls.slice(0, this.maxSize)) {14 const ws = new WebSocket(url);15 await new Promise((resolve, reject) => {16 ws.on("open", () => {17 this.connections.push(ws);18 this.available.push(ws);19 resolve();20 });21 ws.on("error", reject);22 });23 }24 }2526 getConnection() {27 if (this.available.length === 0) {28 throw new Error("No available connections");29 }30 // Round-robin31 const ws = this.available.shift();32 return ws;33 }3435 release(ws) {36 if (ws.readyState === WebSocket.OPEN) {37 this.available.push(ws);38 }39 }4041 async send(data) {42 const ws = this.getConnection();43 try {44 return await new Promise((resolve, reject) => {45 ws.send(data, (err) => {46 if (err) reject(err);47 else resolve();48 });49 });50 } finally {51 this.release(ws);52 }53 }5455 close() {56 this.connections.forEach(ws => ws.close());57 this.connections = [];58 this.available = [];59 }60}6162// Usage63const pool = new WebSocketPool([64 "ws://server1:8080",65 "ws://server2:8080",66 "ws://server3:8080",67]);68await pool.connect();69await pool.send(JSON.stringify({ type: "ping" }));