faye ruby client is not working

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I am using faye on my Rails 2.1 app. And after testing and fixing many things faye ruby client is not working.

This is my server code.

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 } 

This is my client side JS code.

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

This is ruby client code.

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 

Server, JS is working fine. But Ruby client code is not working. If i write it without EM it shows me the error that Event Machine not initialized. If i write it in EM it works but haults the ruby process. If i put EM.stop at the end of client code, it executes but do not publish the message.

How can i solve this issue?

回答1:

You were almost there... You just needed to stop the EM event loop in your callbacks, like this:

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 


回答2:

I finally used HTTP not the Ruby Faye client as described in railscasts episode 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) 

It solves my problem.

NOTE: This solution only works with HTTP but not with HTTPS. If any one find a solution for HTTPS plz update me.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!