Sobes.tech
Junior

What is a web socket?

sobes.tech AI

Answer from AI

WebSocket is a protocol for two-way persistent communication between a client and a server over a single TCP connection. Unlike HTTP, where the connection is established for each request and then closed, WebSockets maintain an open connection, allowing both parties to send data at any time without reopening the connection.

Main advantages:

  • Low latency: Data is transmitted almost instantly.
  • Efficiency: Reduces overhead for establishing connections.
  • Two-way communication: The server can send data to the client without an explicit request.

Examples of use:

  • Chats and messengers
  • Online games
  • Real-time trading platforms
  • Data monitoring (e.g., stock quotes)

The WebSocket protocol starts with a regular HTTP request containing the header Upgrade: websocket. If the server supports WebSockets, it responds with a protocol upgrade confirmation, and the connection switches to the WebSocket protocol.

Example of establishing a connection on the client side (browser):

// Creating a WebSocket connection
const ws = new WebSocket('ws://localhost:8080');

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

// Handling message reception from server
ws.onmessage = (event) => {
  console.log(`Message from server: ${event.data}`);
};

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

// Handling connection close
ws.onclose = () => {
  console.log('WebSocket connection closed');
};

Example of handling connection on the server side (Node.js with ws library):

const WebSocket = require('ws');

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

// Handling new connection
wss.on('connection', (ws) => {
  console.log('Client connected');

  // Handling message from client
  ws.on('message', (message) => {
    console.log(`Received message => ${message}`);

    // Sending response to client
    ws.send(`You sent: ${message}`);
  });

  // Handling disconnection
  ws.on('close', () => {
    console.log('Client disconnected');
  });

  // Handling error
  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
  });

  ws.send('Welcome to WebSocket server!'); // Sending greeting upon connection
});

console.log('WebSocket server started on port 8080');
What is a web socket? — Node.js - sobes.tech