从反向Proxy nginx服务器提供多个Websocket客户端



我有一个nginx实例,该实例可以反向proxies websocket来保护运行WebSocket服务器的内部Python应用程序。我希望多个JavaScript客户端连接到NGINX服务器和Python应用程序来处理多个客户端。当前,当一个JavaScript客户端关闭其WebSocket连接时,所有WebSocket客户端也会死亡。我希望Python应用程序能够为每个客户端维护一个单独的连接。我正在为Python使用WebSockets库。(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)

我通过修改Websockets库以添加最大连接参数来解决此问题。然后,每当客户端断开连接时,只有一个Websocket可以从客户端处理多个会话,我只有在不再有活动的会话时就断开套接字。

最新更新