【问题标题】:Can I start separate port on heroku for EventMachine?我可以在 Heroku 上为 EventMachine 启动单独的端口吗?
【发布时间】:2014-11-21 06:38:30
【问题描述】:

我有一个 ruby​​ on rails 应用程序,其中我为 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 上部署此应用程序可能会出现什么问题?

我们将不胜感激任何建议或帮助。

提前致谢。

【问题讨论】:

    标签: ruby-on-rails-3 heroku websocket eventmachine


    【解决方案1】:

    不,不可能在 heroku 上打开一个端口来运行您的问题中详述的事件机 Web 套接字。路由层只会将端口 80 和 443 代理到您的应用程序,这些端口将在您的应用程序启动时侦听 heroku 提供的任意端口。

    客户端将无法连接到您指定端口上的 Web 套接字。有关在 heroku 中使用 Web 套接字的示例,请参见此处:https://devcenter.heroku.com/articles/websockets

    【讨论】:

    • 感谢@Lukas Eklund 的回答,您能否建议任何其他方法来在heroku 上实现相同的行为?我在 heroku 使用独角兽服务器。
    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多