一、场景
1、使用nginx代理webSocket链接,消息发送和接收都是正常的,但webSocket链接会频繁断开重连
2、如果不使用nginx代理则一切正常
3、程序没有做webSocket心跳处理
如下图
二、nginx代理配置
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;
}
}
三、原因
使用nginx代理webSocket链接,客户端和服务器握手成功后,如果在60s时间内没有数据交互,连接就会自动断开
四、解决
方法1:在nginx配置proxy_read_timeout
时长,最终配置如下
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;
}
}
以上方式只能在设置的时间段内保持链接
方法2:在客户端添加心跳机制