我正在使用padrino websockets(https://github.com/dariocravero/padrino-websockets)为我的网站提供聊天系统,它在我的本地计算机上运行良好。但是,在部署到heroku(免费)之后,websocket不会建立连接并将返回
failed: Connection closed before receiving a handshake response
它在localhost上工作正常,我使用它连接:
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}
答案 0 :(得分:5)
您的Websocket端口(3000)在Heroku上无法公开。
Heroku将对端口80或端口443的任何请求转发到您的网络动态的动态端口,存储在$PORT
bash变量中。
在您的浏览器(客户端)中,尝试替换此行:
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图层共享同一台服务器,它应该有效。