faye ruby​​客户端无法正常工作

我在我的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 } 

这是我的客户端JS代码。

  var client = new Faye.Client('http://localhost:9292/faye'); client.subscribe("/faye/new_chats", function(data) { console.log(data); });  

这是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 

服务器,JS工作正常。 但Ruby客户端代码不起作用。 如果我在没有EM的情况下编写它,它会向我显示Event Machine not initialized的错误。 如果我在EM编写它可以工作但是会影响ruby过程。 如果我将EM.stop放在客户端代码的末尾,它会执行但不会发布消息。

我该如何解决这个问题?

你几乎就在那里……你只需要在你的回调中停止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 

我最终使用HTTP而不是像railscasts第260集中描述的Ruby Faye客户端。

 require 'net/http' message = {:channel => '/faye/new_chats', :data => self.text, :ext => {:auth_token => FAYE_TOKEN}} uri = URI.parse("http://localhost:9292/faye") Net::HTTP.post_form(uri, :message => message.to_json) 

它解决了我的问题。

注意:此解决方案仅适用于HTTP,但不适用于HTTPS。 如果有人找到HTTPS的解决方案PLZ更新我。