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. Setting up a server in Ruby is simple:

require 'faye'

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

bayeux.listen will block if EventMachine is not already running. 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.

The listen() method can take options that specify the key and certificate files to use, which if given make the server respond to SSL traffic.

bayeux.listen(443,
  :key  => 'path/to/ssl.key',
  :cert => 'path/to/ssl.cert'
)

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

Being an event-driven application, Faye only works with event-driven servers. It currently supports the same set of servers as faye-websocket, namely Thin, Rainbows and Goliath. 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 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