Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when a user disconnects from a Faye channel?

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.

like image 772
Abramodj Avatar asked Jun 18 '12 11:06

Abramodj


2 Answers

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.

like image 83
Steve Madsen Avatar answered Nov 01 '22 12:11

Steve Madsen


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.

like image 27
yellowaj Avatar answered Nov 01 '22 11:11

yellowaj