WebSockets | Sheetly Cheat Sheet

Last Updated: November 21, 2025

WebSockets

Real-time bidirectional communication

Client-Side (JavaScript)

// Create WebSocket connection
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', (event) => {
  console.log('Connected to server');
  socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', (event) => {
  console.log('Message from server:', event.data);
});

// Listen for errors
socket.addEventListener('error', (error) => {
  console.error('WebSocket error:', error);
});

// Connection closed
socket.addEventListener('close', (event) => {
  console.log('Disconnected from server');
});

// Send data
function sendMessage(message) {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({ type: 'message', data: message }));
  }
}

Server-Side (Node.js)

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');
  
  // Receive message
  ws.on('message', (data) => {
    console.log('Received:', data);
    
    // Broadcast to all clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
  
  // Client disconnected
  ws.on('close', () => {
    console.log('Client disconnected');
  });
  
  // Send message to client
  ws.send('Welcome to the server!');
});

ReadyState Values

Item Description
0 - CONNECTING Connection not yet established
1 - OPEN Connection established, can send data
2 - CLOSING Connection closing
3 - CLOSED Connection closed

Use Cases

  • Chat applications
  • Live sports scores and updates
  • Collaborative editing tools
  • Real-time gaming
  • Stock price tickers
  • Live notifications
  • IoT device communication

💡 Pro Tips

Quick Reference

Consider Socket.io for easier WebSocket implementation

← Back to Data Science & ML | Browse all categories | View all cheat sheets