WebSocket

WebSocket Server is a technology that enables real-time communication between a web application and a server. It provides a bidirectional data transmission mechanism that allows both the client and the server to send messages to each other simultaneously. Unlike traditional HTTP communication, WebSockets enable full-duplex communication between the client and server, making it ideal for real-time applications.

A WebSocket Server works by establishing a persistent connection between the client and the server using the WebSocket Protocol. This connection remains open, allowing for two-way communication, unlike traditional HTTP communication, which is based on request-response interactions. The WebSocket Protocol allows for low latency and high-frequency data transfer, making it suitable for real-time applications.

Enable WebSocket in Cpanel Server with Nginx

To test a WebSocket server, use

https://ws-playground.netlify.app

On Nginx Proxy connection, to allow websocket, add

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

example

location / {
    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:3000;

    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

}

For laravel reverb, i used following nginx config.

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name ws.serverok.in;

    ssl_certificate /etc/letsencrypt/live/ws.serverok.in/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ws.serverok.in/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_http_version 1.1;
        proxy_pass http://127.0.0.1:8080;

        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Optional: tweak, but keep sane
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        proxy_buffering off;
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *