Padrino websockets + Heroku; 连接在收到握手响应之前关闭

kRI*_*ST- 3 heroku sinatra websocket padrino

我使用padrino websockets(https://github.com/dariocravero/padrino-websockets)为我的网站提供聊天系统,它在我的本地机器上运行良好.但是,在部署到heroku(免费)之后,websocket将不会建立连接并返回

failed: Connection closed before receiving a handshake response
Run Code Online (Sandbox Code Playgroud)

它在localhost上正常工作,我使用它来连接:

connection = new WebSocket('ws://localhost:3000/channel');
Run Code Online (Sandbox Code Playgroud)

但是,当在heroku上使用时:

connection = new WebSocket('ws://******.herokuapp.com:3000/channel');
Run Code Online (Sandbox Code Playgroud)

它返回握手错误(上图)

我的实现服务器端

websocket :channel do
  on :newmessage do |message|
    currentAccount = Account.find_by(lastLoginIP: message["ip"]) rescue nil

    if currentAccount != nil
      broadcast :channel, {
        "name" => currentAccount.nickname,
        "url" => currentAccount.url,
        "image" =>  currentAccount.image,
        "chatmessage" => message["chatmessage"][0..80]
        }
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

在我的主要Padrino app.rb中,这在我的Procfile中.到底是怎么回事?

web: bundle exec puma -t 1:16 -p ${PORT:-3000} -e ${RACK_ENV:-production}
Run Code Online (Sandbox Code Playgroud)

Mys*_*yst 5

您的Websocket端口(3000)在Heroku上不公开.

Heroku将对端口80或端口443的任何请求转发到web dyno的动态端口,存储在$PORTbash变量中.

在您的浏览器(客户端)中,尝试替换此行:

 connection = new WebSocket('ws://localhost:3000/channel');
Run Code Online (Sandbox Code Playgroud)

有了这条线:

 connection = new WebSocket('ws://' + window.document.location.host + 'channel');
Run Code Online (Sandbox Code Playgroud)

或者,如果要同时支持SSL和未加密的Websockets:

 ws_uri = (window.location.protocol.match(/https/) ? 'wss' : 'ws') +
          '://' + window.document.location.host + 'channel';
 connection = new WebSocket(ws_uri)
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序和websocket层共享同一服务器,它应该工作.