WebSockets and Real-Time Communication

WebSockets provide a persistent, bidirectional connection between a client and server. They are useful for chat, live notifications, dashboards, multiplayer applications, and collaborative experiences.

Socket.IO builds higher-level features around real-time communication, including rooms, events, reconnection behavior, and adapters for distributed deployments.

Simple Socket.IO Server
import { Server } from 'socket.io';

const io = new Server(httpServer, {
  cors: { origin: '[https://example.com](https://example.com)' }
});

io.on('connection', (socket) => {
  socket.on('message', (message) => {
    io.emit('message', message);
  });
});
💡 The server listens for connections and broadcasts received messages to connected clients.
Key Takeaways
  • WebSockets enable bidirectional real-time communication.
  • Distributed Socket.IO deployments need an appropriate adapter or shared infrastructure.
  • Authentication and authorization also apply to socket connections.
Knowledge Check

What is a key characteristic of WebSockets?