nginx + python + websockets

2019-04-14 17:08发布

How can I configure nginx (latest version, they say it supports websockets) to support WebSockets.

And how can I use python to run websockets connection.

That what I want:

  • client creates WebSocket with JavaScript;
  • websocket server script runs on python;
  • and nginx in backend of all of this.

Can any body help me?

1条回答
叛逆
2楼-- · 2019-04-14 17:51

I took a quick look at the relevant changeset to Nginx, and it looks like all you need to do to start handling websocket requests is to set up a proxy in your nginx config. So for example:

upstream pythonserver {
    server localhost:5000;
}

server {
    // normal server config stuff...

    location /some/uri/here {
        // Minimum required settings to proxy websocket connections
        proxy_pass http://pythonserver;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        // Other settings for this location
    }
}

This little configuration snippet will proxy incoming websocket traffic to your Python application server, assumed in the example to be listening for local connections on port 5000.

Hope this helps.

查看更多
登录 后发表回答