我正在构建一个同时运行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
我遇到了同样的问题。对我来说,关键似乎是用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
我将精简降级到1.5.1版,它就可以工作了。有线。