我有一个Nginx实例,该实例对Websocket进行反向代理,以保护运行Websocket服务器的内部python应用程序。我希望多个javascript客户端连接到nginx服务器和python应用程序以处理多个客户端。当前,当一个javascript客户端关闭其websocket连接时,所有的websocket客户端也会死亡。我希望python应用能够为每个客户端维护一个单独的连接。我正在将websockets库用于python。 (https://websockets.readthedocs.io/en/stable/intro.html)
nginx服务器配置:
server {
listen 80;
server_name 192.168.1.196;
location / {
root /export/fs/opt/a5/web/static;
index index.html index.htm;
add_header 'Access-Control-Allow-Origin' '*';
}
location /socket.io/ {
proxy_pass http://127.0.0.1:8889;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $http_host;
#proxy_set_header X-Real-IP $remote_addr;
add_header 'Access-Control-Allow-Origin' '*';
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
javascript:
var my_socket = new WebSocket("ws://" + location.host + ":80/socket.io/");
my_socket.onopen = function (event) {
console.log("websocket opened");
};
python:
def start_websocket_server():
ip_address = "127.0.0.1"
web_sock = websockets.serve(handler, ip_address, 8889)
asyncio.ensure_future(web_sock)
print('websocket server created on ' + ip_address)
答案 0 :(得分:0)
我通过修改websockets库以添加max connections参数来解决此问题。然后,无论何时客户端断开连接,由于只有一个websocket可以处理来自客户端的多个会话,因此只有在没有更多活动会话时,我才断开套接字。