Skip links

Most Effective way to Configure WebSocket

WebSocket:

WebSocket provides fully duplex communication over single TCP connection over internet. It is designed to work over HTTP (port: 80) & HTTPS (port: 443) ports. To achieve compatibility, the WebSocket handshake uses the HTTP upgrade header to change from the HTTP protocol to WebSocket protocol. The WebSocket protocol enables interaction between web browser and web server. And facilitating real time data transfer from and to the server. The WebSocket protocol defines as ws:// (WebSocket) and wss:// (WebSocket Secure connection) indicates. This sets up a tunnel, which provides low level hope to hope TCP IP communication through the HTTP port 80 and HTTPS port 443, between the websocket secure client and the WebSocket server.

Why Need WebSocket?

People who are new to WebSocket may ask the question why do we need WebSocket? Since we have HTTP protocol. The answer is HTTP protocol has a flaw: communication only can be initiated by the client. The characteristic of the webscoket is in a way of request is that, it will be troublesome for the client to know if a continuous state changes has happened on the web-server. So we have use pooling. The most typical scenes are like chat room, online gaming, live streaming and etc.

WebSocket Configuration:

1. Upstream Declaration:
NGINX can perform the load balance and distribute user sessions to multiple nodes if your application has several instances running at a time. In the http context in your NGINX configuration, include an upstream block to define the nodes in an upstream group. Upstream node_name { Ip_hash; server 127.0.0.1:8080; server 127.0.0.1:8081; }
2. Virtual Configuration:
The upstream group of servers is declared, a virtual server needs to be configured to direct traffic to it. At min., include the “proxy_pass” directive and named as the upstream group. Because the websocket protocol uses the upgrade header introduced in HTTP/1.1 and we include the “proxy_http_version” directive. server { server_name example.com; location / { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://node_name } }
Benefits:
  • 1. Designed as a web transport for higher level business protocols.
  • 2. Extremely compact and efficient on the wire.
  • 3. Bidirectional communication over TCP connection.
  • 4. Full duplex – Provide low latency delivery of text and binary application data in both direction.

Leave a comment

Explore
Drag