Introduction to isomorphic-ws: A Versatile WebSocket Library
isomorphic-ws is a versatile and powerful WebSocket library that works seamlessly in both Node.js and browser environments. It bridges the gap by providing a unified API, making it easier to write and maintain real-time web applications.
Getting Started with isomorphic-ws
First, you need to install the library using npm:
npm install isomorphic-ws
Basic WebSocket Client Example
Here’s how you can create a basic WebSocket client using isomorphic-ws:
const WebSocket = require('isomorphic-ws'); const ws = new WebSocket('wss://echo.websocket.org'); ws.on('open', function open() { console.log('Connected'); ws.send('Hello WebSocket'); }); ws.on('message', function incoming(data) { console.log(`Received: ${data}`); }); ws.on('close', function close() { console.log('Disconnected'); });
WebSocket Server Example
You can also create a WebSocket server with isomorphic-ws:
const WebSocket = require('isomorphic-ws'); const WebSocketServer = WebSocket.Server; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { console.log(`Received: ${data}`); ws.send(`Echo: ${data}`); }); ws.send('Welcome to the WebSocket server!'); });
Advanced API Usage
Handling Binary Data
const ws = new WebSocket('ws://example.com/socket'); ws.binaryType = 'arraybuffer'; ws.on('message', function incoming(data) { if(data instanceof ArrayBuffer) { console.log('Received binary data:', new Uint8Array(data)); } });
Reconnection Logic
function connect() { const ws = new WebSocket('ws://example.com/socket'); ws.on('open', () => { console.log('Connected to server'); }); ws.on('close', () => { console.log('Connection lost, retrying in 5 seconds...'); setTimeout(connect, 5000); }); ws.on('error', (error) => { console.error('WebSocket error:', error); }); } connect();
Heartbeat (Ping/Pong)
const ws = new WebSocket('ws://example.com/socket'); let isAlive = true; ws.on('pong', () => { isAlive = true; }); const interval = setInterval(() => { if (!isAlive) { return ws.terminate(); } isAlive = false; ws.ping(); }, 30000); ws.on('close', () => { clearInterval(interval); });
Real-World Application Example
Building a Chat Application
Here’s an example of using isomorphic-ws to build a simple chat application:
// Server-side code (Node.js) const WebSocket = require('isomorphic-ws'); const WebSocketServer = WebSocket.Server; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { ws.on('message', (message) => { wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); }); }); // Client-side code (Browser) const ws = new WebSocket('ws://localhost:8080'); ws.onopen = () => { console.log('Connected to the chat server'); }; ws.onmessage = (event) => { console.log('Received:', event.data); }; function sendMessage(message) { ws.send(message); } document.querySelector('#sendButton').addEventListener('click', () => { const message = document.querySelector('#messageInput').value; sendMessage(message); });
With the help of isomorphic-ws, you can effortlessly create real-time web applications with WebSocket support, enhancing user experience and engagement by providing instant updates and communication.
Hash: 44f7dfe921acf4d0404235e8746eff00c98253b917fdbf1b4fc3174b0392b3fa