在同一个脚本中启动并调用Ruby HTTP服务器 [英] Start and call Ruby HTTP server in the same script

查看:442
本文介绍了在同一个脚本中启动并调用Ruby HTTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何启动Ruby Rack应用程序(如Sinatra),并在同一脚本中使用Net :: HTTP或类似的名称。我可以做一些类似...

  require'sinatra / base'
require'net / http'

t = Thread.new do
class App< Sinatra :: Base
get'/'do
'嗨!'
end
end

App.run! :host => 'localhost',:port => 1234
end

sleep 2

放置Net :: HTTP.start('localhost',1234){| http | $。$($ / $)$。 $ p>

...但是睡眠两秒钟并不理想,等待Thin启动。我需要的是某些回调服务器启动或有人有其他建议吗?

解决方案

run!在目前的Sinatra版本使用一个在应用程序启动时调用的块。



使用该回调,您可以执行以下操作:

  require'thread'

def sinatra_run_wait(app,opts)
queue = Queue.new
thread = Thread.new do
Thread.abort_on_exception = true
app.run!(opts)do | server |
queue.push(started)
end
end
queue.pop#blocks直到运行!回调运行
end

sinatra_run_wait(TestApp,:port => 3000,:server =>'webrick')

这对WEBrick来说似乎是可靠的,但是当使用Thin时,在服务器接受连接之前,有时还会调用回调。


I wonder how I could start a Ruby Rack application (such as Sinatra) and call it with Net::HTTP or similar in the same script. Of couse I could do something like...

require 'sinatra/base'
require 'net/http'

t = Thread.new do
    class App < Sinatra::Base
        get '/' do
            'Hi!'
        end
    end

    App.run! :host => 'localhost', :port => 1234
end

sleep 2

puts Net::HTTP.start('localhost', 1234) { |http| http.get('/') }.body

t.join

puts 'Bye!'

...but it doesn't feel optimal to sleep for two seconds, waiting for Thin to start. What I need is some kind of callback when the server has started or does anybody have any other suggestions?

解决方案

run! in current Sinatra versions takes a block that is called when the app is started.

Using that callback you can do this:

require 'thread'

def sinatra_run_wait(app, opts)
  queue = Queue.new
  thread = Thread.new do
    Thread.abort_on_exception = true
    app.run!(opts) do |server|
      queue.push("started")
    end
  end
  queue.pop # blocks until the run! callback runs
end

sinatra_run_wait(TestApp, :port => 3000, :server => 'webrick')

This seems to be reliable for WEBrick, but when using Thin the callback is still sometimes called a little bit before the server accepts connections.

这篇关于在同一个脚本中启动并调用Ruby HTTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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