Can I start separate port on heroku for EventMachine?

280 views Asked by At

I've one ruby on rails application in which I've defined one initializer for EventMachine which will start the EventMachine socket on specified port, here is the code of initializer 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?

And I've listener for this socket in my html file, I'm using html WebSocket in my client side.

Here is the code of my client-side websocket listener:

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.")
      }

I want to deploy my this rails application to Heroku, So is there any problem with EventMachine at Heroku?

Is it possible to start port on Heroku for TCPServer?

What can be the possible issues if I deploy this application on Heroku?

Any advice or help will be appreciated.

Thanks in advance.

1

There are 1 answers

1
Lukas Eklund On BEST ANSWER

No, it is not possible to open a port on heroku to run an event machine web socket as detailed in your question. The routing layer will only proxy ports 80 and 443 through to your app which will be listening on some arbitrary port provided by heroku when your app starts up.

Clients will be unable to connect to the web socket on the port you specified. See here for an example of using web sockets with heroku: https://devcenter.heroku.com/articles/websockets