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

3
我正在使用padrino websockets(https://github.com/dariocravero/padrino-websockets)为我的网站提供一个聊天系统,本地机器上运行良好。然而,在部署到Heroku免费版后,websocket无法连接并返回。
failed: Connection closed before receiving a handshake response

在本地主机上运行良好,我使用以下内容进行连接:

connection = new WebSocket('ws://localhost:3000/channel');

但是,当在Heroku上使用时,需要这样做:

connection = new WebSocket('ws://******.herokuapp.com:3000/channel');

它返回了一个握手错误(如上所示)

我的实现服务器端

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

我的主要Padrino app.rb文件中包含了这个,并且在我的Procfile中也有。发生了什么?

web: bundle exec puma -t 1:16 -p ${PORT:-3000} -e ${RACK_ENV:-production}
1个回答

5

您的Websocket端口(3000)在Heroku上不可公开访问。

Heroku将发送到端口80或443的所有请求转发到存储在$ PORT bash变量中的Web Dyno的动态端口。

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

 connection = new WebSocket('ws://localhost:3000/channel');

使用以下代码行:
 connection = new WebSocket('ws://' + window.document.location.host + 'channel');

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

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

如果您的应用程序和WebSocket层共享同一服务器,则应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接