How do I know when a user disconnects from a Faye channel?

I am trying to use Faye to create a simple chat room with Rails and place it on the hero. So far, I have managed to start the Faye server and make it work with instant messages. The key lines of code that I use are:

Javascript file launched on page load:

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

create.js.erb that starts 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 let you know when the user disconnects from the chat. How can I do it?

I already looked at the Faye website for monitoring , but it is not clear where I should put this code.

+4
source share
2 answers

Event monitoring is in your registry file. Here is an example that I use 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 want in the block that you switch to #bind .

+6
source

You can bind to subscribe and unsubscribe events instead of the disconnect event. Read the warning word at the bottom of the faye monitoring protocols .

This 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 a private pub gem - this will help protect your faye application.

+4
source

All Articles