Faye

Simple pub/sub messaging for the web

Ruby server

Server-side Ruby clients

You can use Faye clients on the server side to send messages to in-browser clients or to other server-side processes. The API is identical to the browser client.

To create a client, just supply the host you want to connect to:

client = Faye::Client.new('http://localhost:9292/faye')

You can then use client.subscribe() and client.publish() to send messages to other clients; the API is similar to the browser client only you need to run the client inside EventMachine:

require 'eventmachine'

EM.run {
  client = Faye::Client.new('http://localhost:9292/faye')

  client.subscribe('/foo') do |message|
    puts message.inspect
  end

  client.publish('/foo', 'text' => 'Hello world')
}

Note that the Ruby client uses EventMachine::Deferrable instead of promises, for example you detect success and failure of a publication like so:

publication = client.publish('/foo', 'text' => 'Hello world')

publication.callback do
  puts 'Message received by server!'
end

publication.errback do |error|
  puts 'There was a problem: ' + error.message
end

If you need to set custom headers to talk to your Bayeux server, use the set_header method:

client.set_header('Authorization', 'OAuth abcd-1234')

The server has its own client attached to it so you can use the server to send messages to browsers. This client has direct access to the server without going over HTTP, and is thus more efficient. To send messages through the server just use the #get_client method.

bayeux.get_client.publish('/email/new', {
  'text'      => 'New email has arrived!',
  'inboxSize' => 34
})

Transport control

When using the client on the server, you can control parts of the transport layer that the browser doesn’t provide access to. For a start, headers added using the client.set_header method will be added to WebSocket connections, not just regular HTTP requests.

You can also request that all connections go via an HTTP proxy:

client = Faye::Client.new(url, {
  :proxy => 'http://username:password@proxy.example.com'
})

You can also set the HTTP_PROXY or HTTPS_PROXY environment variables, which will make all Faye client connections use the given proxy by default; HTTP_PROXY for http: and ws: requests, and HTTPS_PROXY for https: and wss: requests.

Finally, the WebSocket transport can be configured to use protocol extensions; any extension library compatible with websocket-extensions will work. For example, to add permessage-deflate:

require 'permessage_deflate'

client.add_websocket_extension(PermessageDeflate)