Ctrl + C不会杀死Sinatra + EM :: WebSocket服务器 [英] Ctrl+C not killing Sinatra + EM::WebSocket servers

查看:110
本文介绍了Ctrl + C不会杀死Sinatra + EM :: WebSocket服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个同时运行EM :: WebSocket服务器和Sinatra服务器的Ruby应用.我个人认为这两个都可以处理SIGINT.但是,当在同一个应用程序中同时运行两个应用程序时,当我按Ctrl + C组合键时,该应用程序将继续运行.我的假设是其中一个正在捕获SIGINT,而另一个也无法捕获它.不过,我不确定该如何解决.

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.

下面是代码:

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:

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

这篇关于Ctrl + C不会杀死Sinatra + EM :: WebSocket服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆