WebSocket - Real time communication (bidirectional)

    



In 2025, WebSocket will continue to be a popular choice for building real-time applications such as online games, chat apps, and stock tickers.

WebSocket is a standard protocol that enables efficient communication between clients and servers.

🔗 Do you like Techelopment? Check out the website for all the details!


What is WebSocket?

Communication between client and server is the basis of any modern web application. Traditionally, this happens via HTTP requests, where the client sends a request and the server responds with the requested data. However, this approach can be inefficient for applications that require real-time updates, as the client must constantly query the server for new information. To solve this problem, WebSocket technology comes into play.

WebSocket is a communication protocol that allows a bidirectional connection between a client and a server over a single TCP connection. Unlike traditional HTTP requests, WebSocket allows real-time communication, reducing latency and network overhead.


Why use WebSocket?

Using WebSocket in JavaScript is particularly useful in scenarios that require real-time updates, such as:

  • Chat and instant messaging (WhatsApp Web, Slack, Telegram Web)

  • Real-time notifications (alert systems, trading updates)

  • Collaboration applications (Google Docs, shared whiteboarding tools)

  • Multiplayer Online Games

  • Live data monitoring (dashboards, streaming financial data)


How do WebSocket work?

In JavaScript, handling WebSockets is simplified using the WebSocket object, which allows you to create a connection and send/receive messages in real time.

Basic example of a WebSocket connection:


// Creating WebSocket Connection
const socket = new WebSocket('wss://example.com/socket');

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

// Message reception event
socket.addEventListener('message', (event) => {
    console.log('Message received:', event.data);
});

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

// Error event
socket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
});

wss refers to WebSocket Secure (WSS) which is the secure version of the WebSocket (WS) protocol, similar to the relationship between HTTPS and HTTP. It uses SSL/TLS encryption to secure the communication between the client and the server, ensuring that the data exchanged is secure and not interceptable by third parties. It is particularly useful for applications that handle sensitive information, such as messaging services, financial transactions, and authentication.


Create a simple WebSocket server with Node.js

To fully understand how WebSocket work, it is useful to know how to create a server that manages WebSocket connections. This allows for two-way communication between the client and the server, which is essential for applications that require real-time updates without constant HTTP requests.

To create a WebSocket server, we can use the ws library in Node.js:


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

server.on('connection', (ws) => {
    console.log('New connection');

    ws.on('message', (message) => {
        console.log('Message received:', message);
        ws.send('Message received: ' + message);
    });

    ws.on('close', () => {
        console.log('Connection closed');
    });
});


Avoiding common WebSocket mistakes

Working with WebSockets can be very beneficial, but it is important to avoid some common mistakes to ensure stable and efficient communication:

  • Not handling disconnections properly ❌
    • Make sure you implement automatic reconnection if connection is lost. ✅

    • Use events like close and error to detect problems and restore the connection if necessary. For example, this code attempts to reconnect after 3 seconds if an unexpected closure occurs. ✅

      socket.addEventListener('close', () => {
          console.log('Connection closed, trying to reconnect...');
          setTimeout(() => {
              reconnectWebSocket();
          }, 3000);
      });

      socket.addEventListener('error', (event) => {
          console.error('Errore WebSocket:', event);
          socket.close();
      });

      function reconnectWebSocket() {
          socket = new WebSocket('wss://example.com/socket');
      }
  • Don't handle network errors or timeouts ❌
    • Use setTimeout or setInterval to monitor the connection and check if the server is present. ✅

    • Implement logic to retry connections on failure. ✅

  • Sending too many messages in a short time ❌
    • Avoid server overload by limiting the frequency of messages sent. ✅

    • Implement throttling or debounce mechanisms to reduce the number of requests. ✅

  • Don't use WebSocket Secure (WSS) in production ❌
    • Use wss:// instead of ws:// to ensure a secure and encrypted connection, especially on public networks. ✅

  • Lack of authentication and authorization ❌
    • Secure WebSockets with token- or session-based authentication mechanisms. ✅

    • Make sure only authorized users can access certain channels or data. ✅

  • Not closing inactive connections properly ❌
    • Implement a timeout to close idle connections and free up resources. ✅

    • Use the close() method to properly terminate connections that are no longer needed. ✅

Following these best practices will help prevent problems and ensure that your WebSocket application is robust, scalable, and secure.


Popular Applications Using WebSocket

Many of the most popular applications use WebSockets to provide smooth and responsive user experiences:

  • WhatsApp Web and Telegram Web for instant message synchronization

  • Google Docs for collaborative editing of documents in real time

  • TradingView for real-time market price updates

  • Twitch and YouTube Live for live chat and notifications

  • Giochi online multiplayer like Agar.io or Fortnite


Conclusion

WebSockets are an essential technology for real-time communication in modern web applications. Thanks to their efficiency and ease of use in JavaScript, they allow you to create interactive and responsive experiences without the need for continuous HTTP requests. By integrating WebSockets, you can improve the speed and reliability of your applications, making them more engaging for users.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment