Faye

Simple pub/sub messaging for the web

Ruby server

Setting up

All Faye clients need a central messaging server to communicate with; the server records which clients are subscribed to which channels and handles routing of messages between clients. Faye is just like any other Rack app, and you start it by making a rackup file:

# config.ru

require 'faye'
bayeux = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)
run bayeux

Faye runs on MRI and JRuby, and requires at least Ruby 1.9.

The RackAdapter class supports these options during setup:

  • :mount – the path on the host at which the Faye service is available. In this example, clients would connect to http://localhost:9292/faye to talk to the server. The server will handle any request whose path begins with the :mount path; this is so that it can interoperate with clients that use different request paths for different channels.
  • :timeout – the maximum time to hold a connection open before returning the response. This is given in seconds and must be smaller than the timeout on your frontend webserver. Faye uses Thin as its webserver, whose default timeout is 30 seconds.
  • :extensions – (optional) a list of extensions to add to the server, useful when using RackAdapter as middleware.
  • :engine – (optional) the type and parameters for the engine you want to use – see the engines documentation
  • :ping – (optional) how often, in seconds, to send keep-alive ping messages over WebSocket and EventSource connections. Use this if your Faye server will be accessed through a proxy that kills idle connections.

Faye can also be setup as Rack middleware, for example in front of a Sinatra application:

# config.ru

require 'faye'
require File.expand_path('../app', __FILE__)

use Faye::RackAdapter, :mount      => '/faye',
                       :timeout    => 25,
                       :extensions => [MyExtension.new]

run Sinatra::Application

Running your Faye application

Faye supports the same set of servers as faye-websocket. The faye-websocket documentation has plenty of information on running Rack applications with these servers (see Running your socket application), but it’s worth restating here that for some servers you must tell Faye::WebSocket which web server you’re using before booting the application, so it can load adapters for it. For example to load the Thin adapter:

# config.ru

require 'faye'
Faye::WebSocket.load_adapter('thin')

app = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)

run app

Faye uses MultiJson to allow fast JSON processing on both MRI and JRuby. For speed, we recommand using the :oj engine on MRI and the :gson engine on JRuby.