在centos上部署了一个项目,用Nginx来代理websocket,但是websocket连上后30s就会自动断开,在网上查了说Nginx的proxy_read_timeout要设置大点,下面是nginx.conf中关于websocket的配置:
1 2 3 4 5 6 7 8 9 | location / { proxy_set_header Host $host; proxy_pass http://172.16.137.234:8000; proxy_connect_timeout 4; proxy_read_timeout 86400s; proxy_send_timeout 86400s; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } |
我试了无论proxy_read_timeout设置多少,连接还是会在30s的时候自动断开。
我也试了用心跳来保持websocket的连接,下面是代码
前端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | href = "ws://"+baseIP+"/user/connect/" ws = new WebSocket(href) var heartCheck = { timeout: 5000, //5秒发一次心跳 timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); return this; }, start: function(){ var self = this; this.timeoutObj = setTimeout(function(){ ws.send("keepalive"); console.log("发送:keepalive") self.serverTimeoutObj = setTimeout(function(){ ws.close(); }, self.timeout) }, this.timeout) } } ws.onopen = function(){ console.log("websocket已连接") heartCheck.reset().start() ws.send(user_id) } ws.onmessage = function(evt){ heartCheck.reset().start(); if (evt.data != "keepalive"){ msg = JSON.parse(evt.data) that.messageNotice(msg) }else{ console.log("接收:"+evt.data) } } ws.onclose = function(e){ console.log("websocket已断开") console.log(e) } |
这是从网上抄下来的,我设置的是5秒发一次心跳。
后台:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def user_ws_connect(request): """ 接收websocket请求并保存 :param request: :return: """ if request.is_websocket(): while True: message = request.websocket.wait() if not message: break if message.decode() == "keepalive": request.websocket.send("keepalive") else: ... |
页面控制台输出信息:
发送接收6次,也就是30s后连接就断开了。
而且在这30秒内网页响应不了其他请求,必须要等到websocket连接断开才会响应。。。。。
我在开发环境没用Nginx就不会有这种情况,有人知道是怎么回事吗? T-T
回答>>
已经解决。
是gunicorn的原因,gunicorn启动配置项要加上
完整命令:
1 | gunicorn --worker-class=gevent yourapp.wsgi:application |