faye ruby​​客户端不工作

Naz*_*ain 4 javascript ruby rack ruby-on-rails faye

我在我的Rails 2.1应用程序上使用faye.经过测试和修复后,很多东西faye ruby client都无法正常工作.

这是我的服务器代码.

require 'faye'

server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)


EM.run {
  thin = Rack::Handler.get('thin')
  thin.run(server, :Port => 9292)

  server.bind(:subscribe) do |client_id, channel|
    puts "[  SUBSCRIBE] #{client_id} -> #{channel}"
  end

  server.bind(:unsubscribe) do |client_id, channel|
    puts "[UNSUBSCRIBE] #{client_id} -> #{channel}"
  end

  server.bind(:disconnect) do |client_id|
    puts "[ DISCONNECT] #{client_id}"
  end
}
Run Code Online (Sandbox Code Playgroud)

这是我的客户端JS代码.

<script type="text/javascript">
    var client = new Faye.Client('http://localhost:9292/faye');
    client.subscribe("/faye/new_chats", function(data) {
        console.log(data);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

这是ruby客户端代码.

EM.run do
      client = Faye::Client.new('http://localhost:9292/faye')
      publication = client.publish("/faye/new_chats", {
          "user" => "ruby-logger",
          "message" => "Got your message!"
      })
      publication.callback do
        puts "[PUBLISH SUCCEEDED]"
      end
      publication.errback do |error|
        puts "[PUBLISH FAILED] #{error.inspect}"
      end
    end
Run Code Online (Sandbox Code Playgroud)

服务器,JS工作正常.但Ruby客户端代码不起作用.如果我没有EM写它,它会显示错误Event Machine not initialized.如果我把它写在EM它的工作,但hault红宝石过程.如果我放在EM.stop客户端代码的末尾,它会执行但不发布消息.

我该如何解决这个问题?

ndb*_*ent 11

你几乎就在那里......你只需要在你的回调中停止EM事件循环,如下所示:

EM.run do
  client = Faye::Client.new('http://localhost:9292/faye')
  publication = client.publish("/faye/new_chats", {
    "user" => "ruby-logger",
    "message" => "Got your message!"
  })
  publication.callback do
    puts "[PUBLISH SUCCEEDED]"
    EM.stop_event_loop
  end
  publication.errback do |error|
    puts "[PUBLISH FAILED] #{error.inspect}"
    EM.stop_event_loop
  end
end
Run Code Online (Sandbox Code Playgroud)