1

我正在构建一个运行 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
4

2 回答 2

1

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

  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
于 2017-05-09T14:56:56.090 回答
0

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

于 2014-03-15T17:27:46.630 回答