我在rails应用程序上有一个ruby我在其中为EventMachine定义了一个初始化程序,它将在指定的端口上启动EventMachine套接字,这是初始化程序websocket.rb的代码:
Thread.new {
require 'eventmachine'
require 'em-websocket'
EventMachine.run {
host = "0.0.0.0"
port = 2000
$CHANNEL = EventMachine::Channel.new
EventMachine::WebSocket.start(:host => host, :port => port, :debug => true) do |ws|
ws.onopen {
@sid = $CHANNEL.subscribe { |msg| ws.send msg }
# $CHANNEL.push "#{@sid} connected!"
}
ws.onmessage { |msg|
$CHANNEL.push "#{msg}"
}
ws.onclose {
puts "Socket closed."
# this code is commented as we don't want to unsubscribe any socket from channel
# $CHANNEL.unsubscribe(@sid)
}
end
puts "Socket server started..."
}
} unless EventMachine.reactor_running? && EventMachine.reactor_thread.alive?
我在html文件中监听这个套接字,我在客户端使用html WebSocket。
以下是我的客户端websocket侦听器的代码:
if("WebSocket" in window){
var socketURL = 'ws://' + window.location.hostname + ':2000/';
console.log(socketURL);
ws = new WebSocket(socketURL);
ws.onmessage = function(response) {
console.log('Data received:'+response.data);
}
ws.onclose = function() {
console.info('Connection closed');
};
ws.onopen = function() {
console.info('Connection opened');
};
}else{
console.log("You browser doesn't support websockets.")
}
我想将我的这个rails应用程序部署到Heroku,那么Heroku的EventMachine有什么问题吗?
是否可以在Heroku上为TCPServer启动端口?
如果我在Heroku上部署此应用程序可能会出现什么问题?
任何建议或帮助将不胜感激。
提前致谢。
答案 0 :(得分:0)
不,无法在heroku上打开端口来运行事件计算机Web套接字,如问题中所述。路由层只会将端口80和443代理到您的应用程序,该应用程序将在您的应用启动时监听heroku提供的某个任意端口。
客户端将无法连接到您指定的端口上的Web套接字。有关使用带有heroku的Web套接字的示例,请参阅此处:https://devcenter.heroku.com/articles/websockets