【问题标题】:Ctrl+C not killing Sinatra + EM::WebSocket serversCtrl+C 不会杀死 Sinatra + EM::WebSocket 服务器
【发布时间】:2017-05-09 22:56:56
【问题描述】:

我正在构建一个运行 EM::WebSocket 服务器和 Sinatra 服务器的 Ruby 应用程序。就个人而言,我相信这两者都具备处理 SIGINT 的能力。但是,当在同一个应用程序中运行两者时,当我按 Ctrl+C 时应用程序会继续运行。我的假设是其中一个正在捕获 SIGINT,阻止另一个也捕获它。不过,我不确定如何修复它。

简而言之,代码如下:

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

【问题讨论】:

  • 感谢分享。我根据那个 SO 问题/接受的答案尝试了一些捕获 INT 和 TERM 的变体,但似乎没有什么对我有用。

标签: ruby websocket sinatra eventmachine sigint


【解决方案1】:

我有同样的问题。对我来说,关键似乎是在反应器循环中使用 signals: false 启动 Thin:

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

这是一个简单聊天服务器的完整代码:

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】:

    我将 Thin 降级到 1.5.1 版,它可以正常工作。有线。

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多