【问题标题】:Serving multiple websocket clients from a reverse-proxy nginx server从反向代理 nginx 服务器为多个 websocket 客户端提供服务
【发布时间】:2023-03-13 05:10:01
【问题描述】:

我有一个 nginx 实例,它反向代理 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");
};

蟒蛇:

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)

【问题讨论】:

    标签: javascript python nginx websocket server


    【解决方案1】:

    我通过修改 websockets 库来添加最大连接参数来解决这个问题。然后,任何时候客户端断开连接,因为只有一个 websocket 处理来自客户端的多个会话,所以我只在没有更多活动会话时断开套接字。

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2020-10-31
      • 2016-10-28
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      相关资源
      最近更新 更多