操作电缆无法连接(无法升级到WebSocket)

set*_*thi 10 ruby-on-rails nginx ruby-on-rails-5 actioncable

我在使用这些日志消息连接到非开发环境中的websocket时遇到问题

Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )

Finished "/cable/"[non-WebSocket] for 127.0.0.1 at 2016-07-06 09:44:29 +1000
Run Code Online (Sandbox Code Playgroud)

我稍微调试了一下,发现浏览器发送的请求/ javascript与unicorn收到的请求(与nginx一起运行)不完全相同.

浏览器的请求标头是

GET ws://cc-uat.com.au/cable HTTP/1.1
Host: cc-uat.com.au
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://cc-uat.com.au
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: <Lot of cookies>
Sec-WebSocket-Key: QGdJkYIA2u7vtmMVXfHKtQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: actioncable-v1-json, actioncable-unsupported
Run Code Online (Sandbox Code Playgroud)

这里的连接是'升级'但是websocket请求的连接'已关闭'(可能是nginx搞乱了吗?)

websocket驱动程序中的这段代码失败了

def self.websocket?(env)
      connection = env['HTTP_CONNECTION'] || ''
      upgrade    = env['HTTP_UPGRADE']    || ''

      env['REQUEST_METHOD'] == 'GET' and
      connection.downcase.split(/ *, */).include?('upgrade') and
      upgrade.downcase == 'websocket'
end
Run Code Online (Sandbox Code Playgroud)

更新

这是我的nginx配置

upstream app {
    server unix:/home/osboxes/sites/actioncable-examples/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/osboxes/sites/actioncable-example/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
    }


    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}
Run Code Online (Sandbox Code Playgroud)

我在/ cable上安装了actioncable服务器

mount ActionCable.server => "/cable"
Run Code Online (Sandbox Code Playgroud)

通过nginx更改,我能够成功进行握手,但服务器无法发送心跳并且连接不断下降.

Started GET "/cable" for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
Run Code Online (Sandbox Code Playgroud)

小智 3

您是否已将config.action_cable.allowed_request_originsin production.rb 设置为允许来自生产域的连接?在我的 nginx.conf 中还有

proxy_set_header X-Real-IP $remote_addr;  
proxy_set_header X-Forwarded-Proto http;
Run Code Online (Sandbox Code Playgroud)

我不完全确定它们是否真的需要,但它对我有用。