【发布时间】:2018-06-13 11:00:10
【问题描述】:
我真的很想用 nginx 配置 tornado websocket 连接配置,最后我遇到了一个问题,但我无法修复它。我的配置有什么错误吗? 这是我的 websocket.py:
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", ChatSocketHandler)
]
settings = dict(
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
template_path=os.path.join(os.path.dirname(__file__),
"templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=False,
debug = True
)
super(Application, self).__init__(handlers, **settings)
class ChatSocketHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self, *args, **kwargs):
print('connection opened')
def on_close(self):
print('connection closed')
def on_message(self, message):
print(message)
self.write_message(message)
这是我的客户端脚本:
<script>
let url = "ws://104.131.115.151:8888/";
let socket = new WebSocket(url);
socket.onmessage = function(event) {
console.log(event);
};
socket.onopen = function () {
console.log('opend');
socket.send('Hello World')
};
socket.onclose = function () {
console.log('closed');
};
</script>
在我的网络浏览器控制台中:
opened
closed
在没有 nginx 配置的本地运行时:
opened
MessageEvent{...}
这是我的 nginx 配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream pythonserver {
server 127.0.0.1:8888;
}
server{
listen 80;
server_name 209.97.139.107;
location /chatsocket {
proxy_pass http://pythonserver;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
keepalive_timeout 90;
proxy_cache off;
proxy_buffering off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
include uwsgi_params;
uwsgi_pass unix:/home/apideveloper/api/app.sock;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/home/apideveloper/api/app.sock;
}
}
我也在使用https://digitalocean.com云和我的服务器网址http://209.97.139.107/
【问题讨论】:
标签: javascript nginx websocket tornado