WebSockets with Passenger 5.0.30

31 views
Skip to first unread message

Arindam Mukherjee

unread,
Oct 14, 2016, 1:44:06 AM10/14/16
to Phusion Passenger Discussions
Sorry to be posting again with the same problems because some of my earlier questions went unanswered, likely because they weren't detailed enough.

I am trying to support a WebSocket interface to my Rails application. I am on Rails 4 with no plans of moving to Rails 5 immediately. I use Phusion Passenger 5.0.30 behind nginx.

I want to use em-websocket (+eventmachine) to build this support. What are Passenger configuration settings that I must use?

    server {
      listen 80 default_server;
      server_name ergo;
      root /home/user/www/testapp/public;
      passenger_enabled on;
      passenger_app_env development;
    
      passenger_max_preloader_idle_time 0;
    
      location /notify {
        proxy_pass http://ergo:3004/notify;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        passenger_force_max_concurrent_requests_per_process 0;
      }
    }

Using the above configuration, and the following code for start the EM loop in `config/initializers/event_machine_init.rb`, I cannot get the websocket server to work. Are there additional config changes needed?

    require 'eventmachine'
    require 'em-websocket'
    
    module EventMachineInit
      def self.start
        if defined?(PhusionPassenger)
          PhusionPassenger.on_event(:starting_worker_process) do |forked|
          # for passenger, we need to avoid orphaned threads
            if forked && EM.reactor_running?
              EM.stop
            end
    
            Thread.new do
              puts "Starting EventMachine thread"
              EM.run do
                EM::WebSocket.run(host: "0.0.0.0", port: 3004) do |ws|
                  ws.onopen do |handshake|
                    puts "WebSocket connection open"
                    ws.send "Hello Client, you connected to #{handshake.path}"
                  end
    
                  ws.onclose { puts "WebSocket connection closed" }
    
                  ws.onmessage do |msg|
                    puts "Received message: #{msg}"
                    ws.send "Pong: #{msg}"
                  end
                end
              end
            end
            die_gracefully_on_signal
          end
        end
      end
    
      def self.die_gracefully_on_signal
        Signal.trap("INT")  { EM.stop }
        Signal.trap("TERM") { EM.stop }
      end
    end


Reply all
Reply to author
Forward
0 new messages