Why WebSocket is Critical for Real-time Collaboration in WordPress

Sagar Prajapati
Why WebSocket is Critical for Real-time Collaboration in WordPress featured image

Table of Contents

    A WebSocket is a communication protocol that enables full-duplex, real-time communication between a client (typically a web browser) and a server over a single TCP connection. Unlike traditional HTTP connections, which are stateless and request-response based, WebSocket connections remain open, allowing continuous bidirectional communication.

    WebSocket: History and Introduction

    WebSocket was standardized by the Internet Engineering Task Force (IETF) in 2011 as RFC 6455. However, its history dates back to the early 2000s, when it was developed to overcome the limitations of traditional web communication.

    In the early days of the web, HTTP protocol was used for communication between clients and servers. However, this protocol’s request-response model needed to be more suitable for real-time applications requiring constant communication. Techniques like polling and long polling were introduced to address this limitation, but they had drawbacks, such as high latency and increased overhead.

    WebSocket emerged as a more efficient alternative to these techniques. It established a persistent connection between the client and server, enabling low-latency bidirectional communication. The WebSocket protocol starts with an HTTP handshake, which upgrades the connection to WebSocket. Once established, the connection allows for real-time data exchange without additional HTTP requests.

    WebSockets have gained popularity over the years due to their ability to provide real-time, event-driven communication. They have been widely adopted in various applications, including chat platforms, collaborative tools, real-time dashboards, and more. Modern web browsers support the protocol and have server-side implementations in various programming languages.

    • Chat applications like WhatsApp, Facebook Messenger, and Slack use WebSockets to allow users to send and receive messages in real-time.
    • Streaming media applications like Twitch, YouTube, and Netflix use WebSockets to deliver live or on-demand video and audio to users. 
    • Collaboration tools like Google Docs, Slack, and Trello use WebSockets to allow users to work on shared documents and projects in real-time. 
    • Game engines like Unity and Unreal Engine use WebSockets to allow players to interact with each other in real-time. 
    • Data visualization tools like Tableau and QlikView use WebSockets to allow users to interact with live data in real-time.

    WebSockets Explained

    WebSocket enables real-time, bidirectional communication between a client and a server over a single TCP connection. Here are some key features and functionalities of WebSocket:

    • Full-duplex communication: WebSocket allows the client and the server to send data to each other simultaneously, in real-time. Unlike traditional HTTP connections, where communication is request-response based, WebSocket enables a persistent connection where data can be pushed from either end without explicit requests.
    • Low latency: WebSocket provides low-latency communication by eliminating the need for frequent polling or long polling techniques. With WebSocket, data can be transmitted instantly, reducing delays and improving the responsiveness of real-time applications.
    • Efficiency: WebSocket reduces overhead by establishing a persistent connection between the client and the server. Once the initial connection is established, subsequent data transfers do not require the overhead of establishing new connections for each request.
    • Bi-directional communication: WebSocket supports data flow in both directions. Clients can send messages to the server, and the server can push updates or notifications to the clients. This bidirectional nature enables interactive and collaborative applications, such as chat, multiplayer gaming, collaborative editing, and real-time dashboards.
    • Event-driven architecture: WebSocket is designed around an event-driven model. It allows the server to send data to clients instantly when an event occurs, rather than relying on clients repeatedly polling for updates. This event-driven architecture is particularly suitable for applications that require real-time data synchronization or instant notifications.
    • Wide browser support: WebSocket is supported by most modern web browsers, making it a reliable and cross-platform solution for real-time communication. This widespread support allows developers to build real-time web applications seamlessly across browsers and devices.

    Overall, WebSocket simplifies the implementation of real-time web applications by providing a standardized protocol for efficient, bidirectional, and low-latency communication between clients and servers. It has become a fundamental technology for building interactive and collaborative web applications.

    The Importance of WebSockets and Web Servers

    WebSockets and web servers are integral components in the architecture of web applications. WebSockets enable real-time, bidirectional communication, enhancing the user experience and enabling scalable, efficient, and interactive applications. 

    Web servers handle incoming requests, manage resources, serve static files, deploy applications, and ensure scalability and reliability. Together, they form the foundation for modern web development and enable the creation of dynamic and engaging web applications.

    Other Methods besides the WebSocket

    Besides WebSocket, several other methods or protocols are commonly used for communication between clients and servers in web applications. Here are a few notable ones:

    1. HTTP (AJAX): The Hypertext Transfer Protocol (HTTP) is the foundation of communication on the web. Although it is a request-response protocol, it can be combined with techniques like Asynchronous JavaScript and XML (AJAX) to achieve near real-time updates. AJAX allows clients to send asynchronous requests to the server and receive responses without reloading the entire web page. This approach is commonly used for dynamic content updates and partial page rendering.
    2. Server-Sent Events (SSE): Server-Sent Events is a unidirectional communication protocol that allows servers to push data to clients over a single HTTP connection. It provides a streaming mechanism where the server can continuously send updates to the client as new data becomes available. SSE is well-suited for scenarios where the server primarily sends updates or notifications to clients, such as real-time feeds or event broadcasting.
    3. Long Polling: In this technique, the client sends a request to the server, and the server holds the request open until new data is available or a timeout occurs. Once new data is available, the server responds with the updated data, and the client immediately sends a new request. Long polling simulates a push-like behaviour by keeping the connection open for an extended period, reducing the delay between updates. However, it still involves periodic requests and can be less efficient than WebSockets or SSE.
    4. WebRTC: Web Real-Time Communication (WebRTC) is a browser-based technology that enables peer-to-peer communication between browsers without needing plugins or additional software. WebRTC supports real-time audio, video, and data transfer directly between clients. It is commonly used for video conferencing, voice calling, and peer-to-peer file-sharing applications.
    5. MQTT: Message Queuing Telemetry Transport (MQTT) is a lightweight messaging protocol designed for efficient communication in constrained environments, including IoT (Internet of Things) devices. MQTT follows a publish-subscribe model, where clients subscribe to specific topics and receive messages published by publishers. It provides reliable, low-latency messaging and is widely used for real-time data exchange in IoT applications.
    Image Credit: wikitechy.com

    Those above are just a few examples of communication methods used in web applications. The choice of method depends on the application’s specific requirements, including real-time needs, data volume, scalability, and compatibility with client and server technologies.

    Why are WebSockets more reliable for building Real-Time Collaboration in WordPress?

    WebSockets play a crucial role in enabling real-time collaboration in WordPress. They are a more reliable solution to building real-time collaboration in WordPress than traditional approaches such as AJAX or long polling. 

    AJAX polling is a technique where the client periodically requests data from the server. This can be effective for small amounts of data but slow and inefficient for large amounts of data or real-time applications. Long polling is a variation of AJAX polling where the client keeps the connection open with the server until the server has data to send. This can improve performance over AJAX polling, but it can still be inefficient for real-time applications.

    WebSockets overcome AJAX and long polling limitations by providing a persistent connection between the client and server. This allows for two-way communication in real-time, which is essential for real-time collaboration applications.

    Here are some reasons why WebSocket is a reliable solution for real-time collaboration:

    • Real-Time Communication: WebSockets provide immediate and bidirectional communication between clients and servers. This allows users to collaborate in real-time, seeing updates from others instantly. Whether live chat, document editing, or collaborative project management, WebSocket ensures smooth and instantaneous communication.
    • High Performance: WebSocket’s persistent connection eliminates the need for frequent or long polling, reducing latency and overhead. It enables efficient data transfer, ensuring updates are delivered quickly and reliably. This is especially important for real-time collaboration, where timely information sharing is critical.
    • Security: WebSocket utilizes the same security mechanisms as HTTP, such as SSL/TLS encryption, ensuring the confidentiality and integrity of data exchanged between clients and servers. This makes WebSocket a secure solution for real-time collaboration in WordPress.
    • Scalability: WebSocket’s efficient and low-latency communication allows for scaling real-time collaboration applications. By minimizing unnecessary requests and optimizing data transfer, WebSocket enables the system to handle more concurrent users without compromising performance.

    WebSocket Configuration for Web Servers

    Configuring WebSocket support may vary depending on your specific web server. Here are some general guidelines for enabling WebSocket support on popular web servers:

    Apache HTTP Server:

    • Ensure that you have the mod_proxy and mod_proxy_wstunnel modules enabled.
    • In your Apache configuration file, add a proxy rule to forward WebSocket connections to the appropriate backend server. For example:
    <VirtualHost *:443>
      RewriteEngine on
      RewriteCond ${HTTP:Upgrade} websocket [NC]
      RewriteCond ${HTTP:Connection} upgrade [NC]
      RewriteRule .* "wss:/localhost:8080/$1" [P,L]
      
      ProxyPass / https://localhost:8080/
      ProxyPassReverse / https://localhost:8080/
      ProxyRequests off
    </VirtualHost>
    • Restart the Apache server to apply the changes.

    NGINX:

    • Ensure you have a recent version of NGINX (1.3.13 or later) that includes the proxy and proxy_http modules.
    • In your NGINX configuration file, add a location block to proxy WebSocket connections to the backend server. For example:
     location /ws {
            # redirect all traffic to localhost:8080;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Forwarded-Proto $scheme;
    
            proxy_pass http://127.0.0.1:8080$request_uri;
            proxy_redirect off;
            proxy_read_timeout 86400;
    
            # enables WS support
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
    
            # prevents 502 bad gateway error
            proxy_buffers 8 32k;
            proxy_buffer_size 64k;
    
            reset_timedout_connection on;
    
            error_log /var/log/nginx/wss_error.log;
            access_log /var/log/nginx/wss_access.log;
        }
    • Reload or restart NGINX to apply the configuration changes.

    Microsoft IIS:

    • Ensure that WebSocket Protocol is installed as a server role in the Windows Server Manager.
    • In the IIS Manager, select the website or application where you want to enable WebSocket.
    • Open the “WebSocket” feature and make sure it is enabled.
    • Optionally, you can configure WebSocket-specific settings such as request timeout or buffer size.
    • Save the changes and restart IIS to apply the WebSocket configuration.

    Enable WebSocket with Node:

    Node.js script named server.js; you can run it using the following command in the terminal:

    node server.js

    Here’s an example of a server.js script using the ws library to handle WebSocket connections:

    const WebSocket = require('ws');
    const wss = new WebSocket.Server({ port: 8080 });
    
    wss.on('connection', (ws) => {
      console.log('WebSocket connected');
    
      ws.on('message', (message) => {
        console.log('Received message:', message);
        // Handle incoming messages from clients
      });
    
      ws.on('close', () => {
        console.log('WebSocket disconnected');
        // Handle WebSocket disconnections
      });
    });
    
    console.log('WebSocket server started on port 8080);

    This will start the WebSocket server on port 8080, and you can modify the server logic to suit your application’s needs. Remember to adjust the port number if you prefer a different one.

    Once the Node.js server is running, you can configure your web server to proxy WebSocket connections to localhost:8080, as explained in the previous instructions for Apache, NGINX, or Microsoft IIS.

    Make sure to replace localhost:8080 in the web server configurations with the appropriate address and port where your Node.js server is running.

    Note: Ensure you have the ws library installed in your Node.js project by running npm install ws in the terminal before running the server.

    Conclusion

    WebSockets provide a reliable and efficient solution for real-time collaboration in WordPress. They enable immediate and bidirectional communication, ensuring smooth collaboration and timely updates. With their low latency, high performance, and scalability, WebSockets enhance the user experience and enable real-time collaboration features in WordPress applications.

    Get all the collaboration features of Google Docs in WordPress
    right-bar-image-blog Start 14-Day FREE Trial
    • Multicollab can increase 2x speed to your publishing workflow.
    • WordPress is built and designed for publishing while Google Docs is not!
    • Protect your content within the safety of your company’s infrastructure.
    • Async collaboration with remote editorial teams is the future of publishing.
    Author
    Sagar is a Lead WordPress Developer with over a decade-long experience crafting tailored WordPress solutions. He is proficient in WP-CLI for streamlined development workflows, Websocket and Real-time technologies.