Sobes.tech
Junior

What are sockets used for in web development?

sobes.tech AI

Answer from AI

For two-way data exchange between a client (browser) and a server in real-time. Unlike traditional HTTP, where the client initiates a request and the server responds, sockets allow the server to send data to the client at any time without a prior request.

Examples of use:

  • Chat applications: Instant delivery of messages between users.
  • Online games: Synchronization of player states and game world in real-time.
  • Trading platforms: Updating stock or cryptocurrency quotes without page reload.
  • Notifications: Sending push notifications to users when the order status changes, new messages, etc.
  • Collaborative document editing: Synchronization of changes between multiple users.

Sockets are implemented over the TCP protocol and typically use the WebSocket protocol, which provides a persistent connection between the client and server after the initial HTTP handshake.

// Example client code for establishing a WebSocket connection
const ws = new WebSocket('ws://localhost:8080'); // WebSocket server address

ws.onopen = () => {
  // Connection established
  console.log('WebSocket connection established');
  ws.send('Hello, server!'); // Sending a message to the server
};

ws.onmessage = (event) => {
  // Message received from server
  console.log('Message received from server:', event.data);
};

ws.onclose = (event) => {
  // Connection closed
  if (event.wasClean) {
    console.log(`Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    console.error('Connection interrupted');
  }
};

ws.onerror = (error) => {
  // Error during WebSocket operation
  console.error('WebSocket error:', error);
};

WebSocket connection has low overhead compared to constant HTTP requests (polling or long polling), making it more efficient for applications requiring frequent real-time data exchange.