2011-12-20 83 views
4

我在Rails 2.1应用程序上使用faye。经过测试和修复很多东西faye ruby client不起作用。faye ruby​​客户端无法正常工作

这是我的服务器代码。

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代码。

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

这是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放在客户端代码的末尾,它会执行但不发布消息。

我该如何解决这个问题?

回答

3

在railscasts集260

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不是红宝石王菲客户端。

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

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 
+0

我希望我可以给你10分以上!你真的帮助了我,谢谢! – siekfried 2014-01-28 13:49:20