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

纵然是瞬间 提交于 2019-12-11 11:16:35

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/19299932/ctrlc-not-killing-sinatra-emwebsocket-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!