是否可以从Thin / Rack / Sinatra访问Ruby EventMachine通道?

| 我希望利用Sinatra为内部项目构建一个简单的RESTful通知系统。我过去曾使用EventMachine频道订阅/发布事件,但在我以前的所有案例中,我都是直接使用EventMachine。 有谁知道可以从Sinatra应用程序甚至是某些Rack中间件创建,订阅和发布到EventMachine频道(在Thin中运行)吗?     
已邀请:
看看async_sinatra。 基本上,要使在Thin中运行EventMachine成为可能,您需要使它意识到要异步处理请求。 Rack协议在设计上是同步的,Thin期望在处理程序返回时完成请求。有多种方法可以让Thin知道您要异步处理请求(有关示例,请参见think_async),而async_sinatra使其变得非常容易。     
布莱恩 您可以使用em-http-request库(https://github.com/igrigorik/em-http-request),这将允许您引用在A.同一服务器B. a上运行的特定EventMachine应用程序。不同的服务器,或C.随便什么地方。
require \'eventmachine\'
require \'em-http-request\'
require \'sinatra/base\'
require \'thin\'

class ServerClass < EventMachine::Connection
  def initialize(*args)
    # ruby singleton - store channel data in global hash
    ($channels ||= [])
  end

  def post_init
    puts \"initialized\"
    $cb.call(\"initialized\");
  end

  def receive_data(data)
    # got information from client connection
  end

  def channel_send(msg,channel)
    $channels[channel].send_data(msg)
  end

  def channels_send(msg)
    $channels.each{|channel| channel.send_data(msg)}
  end

  def unbind
    # puts user left
  end

end

EventMachine.run do
  $cb = EM.callback {|msg| puts msg #do something creative}
  $ems = EventMachine::start_server(\'0.0.0.0\',ServerClass,args)

  class App < Sinatra::Base
    set :public, File.dirname(__FILE__) + \'/public\'

    get \'/\' do
      erb :index          
    end

  end

  App.run!({:port => 3000})

end
上面是一个基本的线框。根据要发送数据的方式,可以使用WebSockets(em-websocket)并在登录时绑定每个用户(必须添加登录系统),也可以将其用于任何用途。只要您对Eventmachine对象(连接,WebSocket,通道)具有全局引用,就可以从应用程序内部传递消息。 顺便说一句-添加EventMachine.run do; .... end循环是可选的,因为Thin仍然会这样做。不过,这有助于了解其工作原理。 祝好运     

要回复问题请先登录注册