How to know when a user disconnects from a Faye channel?
Asked Answered
T

2

5

I'm trying to use Faye to build a simple chat room with Rails, and host it on heroku. So far I was able to make the Faye server run, and get instant messaging to work. The crucial lines of code that I'm using are:

Javascript file launched when the page loads:

$(function() {
  var faye = new Faye.Client(<< My Feye server on Heoku here >>);
  faye.subscribe("/messages/new", function(data) {
    eval(data);
  });
});

create.js.erb, triggered when the user sends a message

<% broadcast "/messages/new" do %>
  $("#chat").append("<%= j render(@message) %>");
<% end %>

Everything is working fine, but now I would like to notify when a user disconnects from the chat. How should I do this?

I already looked in the Faye's website about monitoring, but it's not clear where should I put that code.

Threecolor answered 18/6, 2012 at 11:3 Comment(0)
C
6

Event monitoring goes in your rackup file. Here is an example I'm using in production:

Faye::WebSocket.load_adapter('thin')
server = Faye::RackAdapter.new(mount: '/faye', timeout: 25)

server.bind(:disconnect) do |client_id|
  puts "Client #{client_id} disconnected"
end

run server

Of course you can do whatever you like in the block you pass to #bind.

Coker answered 18/6, 2012 at 21:32 Comment(2)
Thanks for your help, but this makes my app crashing, both locally and on heroku. The error just says that the method "bind" does not exists: 'config.ru:24:in block in <main>: undefined method bind' for #<Faye::RackAdapter:0x007fe95ce6cb00> (NoMethodError)'Threecolor
Check the versions of the Faye gems that you're using. The code above definitely works with faye 0.8.2 and faye-websocket 0.4.5.Coker
P
4

You may want to bind to the subscribe and unsubscribe events instead of the disconnect event. Read the word of warning on the bottom of the faye monitoring docs.

This has worked well for me:

server.bind(:subscribe) do |client_id|
  # code to execute
  # puts "Client #{client_id} connected"
end

server.bind(:unsubscribe) do |client_id|
  # code to execute
  # puts "Client #{client_id} disconnected"
end

I also recommend using the private pub gem - this will help secure your faye app.

Poppas answered 17/1, 2013 at 22:26 Comment(1)
can you publish to a given channel? I tried this but I only get timeouts [ERROR] [Faye::RackAdapter] Timeout::ErrorBhagavadgita

© 2022 - 2024 — McMap. All rights reserved.