Matt Huggins
Matt Huggins

Reputation: 83299

Ctrl+C not killing Sinatra + EM::WebSocket servers

I'm building a Ruby app that runs both an EM::WebSocket server as well as a Sinatra server. Individually, I believe both of these are equipped to handle a SIGINT. However, when running both in the same app, the app continues when I press Ctrl+C. My assumption is that one of them is capturing the SIGINT, preventing the other from capturing it as well. I'm not sure how to go about fixing it, though.

Here's the code in a nutshell:

require 'thin'
require 'sinatra/base'
require 'em-websocket'

EventMachine.run do
  class Web::Server < Sinatra::Base
    get('/') { erb :index }
    run!(port: 3000)
  end

  EM::WebSocket.start(port: 3001) do |ws|
    # connect/disconnect handlers
  end
end

Upvotes: 1

Views: 409

Answers (2)

rainkinz
rainkinz

Reputation: 10393

I had the same issue. The key for me seemed to be to start Thin in the reactor loop with signals: false:

  Thin::Server.start(
    App, '0.0.0.0', 3000,
    signals: false
  )

This is complete code for a simple chat server:

require 'thin'
require 'sinatra/base'
require 'em-websocket'

class App < Sinatra::Base
  # threaded - False: Will take requests on the reactor thread
  #            True:  Will queue request for background thread
  configure do
    set :threaded, false
  end

  get '/' do
    erb :index
  end
end


EventMachine.run do

  # hit Control + C to stop
  Signal.trap("INT")  {
    puts "Shutting down"
    EventMachine.stop
  }

  Signal.trap("TERM") {
    puts "Shutting down"
    EventMachine.stop
  }

  @clients = []

  EM::WebSocket.start(:host => '0.0.0.0', :port => '3001') do |ws|
    ws.onopen do |handshake|
      @clients << ws
      ws.send "Connected to #{handshake.path}."
    end

    ws.onclose do
      ws.send "Closed."
      @clients.delete ws
    end

    ws.onmessage do |msg|
      puts "Received message: #{msg}"
      @clients.each do |socket|
        socket.send msg
      end
    end


  end

  Thin::Server.start(
    App, '0.0.0.0', 3000,
    signals: false
  )

end

Upvotes: 1

KF Lin
KF Lin

Reputation: 1323

I downgrade thin to version 1.5.1 and it just works. Wired.

Upvotes: 0

Related Questions