nginx proxy webSocket link, webSocket frequently disconnects and reconnects


1. Scene

1. Use nginx to proxy the webSocket link. Message sending and receiving are normal, but the webSocket link will frequently disconnect and reconnect.

2. If you don’t use nginx proxy, everything will be normal.

3. The program does not perform webSocket heartbeat processing

As shown below

Insert image description here


2. nginx proxy configuration

upstream cloud_ass {
    
    
	#ip_hash;
	server 192.168.1.233:8087;
	server 192.168.1.243:8087;
}

server {
    
    
    listen       8600;
    server_name  localhost;

    location / {
    
    
        root   html;
        index  index.html index.htm;
    }
    
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    
    
        root   html;
    }
	

	location ~* /FS_WEB_ASS/* {
    
    
		proxy_pass http://cloud_ass;
		
		# WebScoket Support
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "upgrade";
		
		proxy_set_header Origin "";
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header Host $http_host;
		proxy_set_header X-NginX-Proxy true;
		break;
	}
}

3. Reasons

Use nginx to proxy the webSocket link. After the client and server handshake successfully, if there is no data interaction within 60s, the connection will be automatically disconnected.


4. Solve

Method 1: Configure proxy_read_timeoutthe duration in nginx, the final configuration is as follows

upstream cloud_ass {
    
    
	#ip_hash;
	server 192.168.1.233:8087;
	server 192.168.1.243:8087;
}

server {
    
    
    listen       8600;
    server_name  localhost;

    location / {
    
    
        root   html;
        index  index.html index.htm;
    }
    
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    
    
        root   html;
    }
	

	location ~* /FS_WEB_ASS/* {
    
    
		proxy_pass http://cloud_ass;
		
		# WebScoket Support
		proxy_http_version 1.1;
		# webscoekt超时时间,如果没有做心跳之类的动作需要配置,否则webSocket会频繁断开重连
		proxy_read_timeout 700s;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "upgrade";
		
		proxy_set_header Origin "";
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header Host $http_host;
		proxy_set_header X-NginX-Proxy true;
		break;
	}
}

The above method can only maintain the link within the set time period

Method 2: Add a heartbeat mechanism on the client

Guess you like

Origin blog.csdn.net/weixin_52116015/article/details/132426499