Skip to content
Standards-compliant WebSocket client and server
Find file
Pull request Compare This branch is even with faye:goliath.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
examples
ext/faye_websocket_mask
lib/faye
spec
vendor
.gitignore
.gitmodules
CHANGELOG.txt
Gemfile
README.rdoc
Rakefile
faye-websocket.gemspec

README.rdoc

Faye::WebSocket

This is a robust, general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket servers and clients in Ruby. It does not provide a server itself, but rather makes it easy to handle WebSocket connections within an existing Rack application. It does not provide any abstraction other than the standard WebSocket API.

Currently, the following web servers are supported, and can be accessed directly or via HAProxy:

The server-side socket can process draft-75, draft-76, hybi-07 and later versions of the protocol. It selects protocol versions automatically, supports both text and binary messages, and transparently handles ping, pong, close and fragmented messages.

Accepting WebSocket connections in Rack

You can handle WebSockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual WebSocket methods for receiving and sending messages. For example this is how you'd implement an echo server:

# app.rb
require 'faye/websocket'

App = lambda do |env|
  if env['HTTP_UPGRADE']
    ws = Faye::WebSocket.new(env)

    ws.onmessage = lambda do |event|
      ws.send(event.data)
    end

    ws.onclose = lambda do |event|
      p [:close, event.code, event.reason]
      ws = nil
    end

    # Return async Rack response
    socket.rack_response

  else
    # Normal HTTP request
    [200, {'Content-Type' => 'text/plain'}, ['Hello']]
  end
end

This is a standard Rack app, so it can be run using a config.ru file. However, so that incoming requests can be properly prepared to process WebSocket connections, you need to tell Faye::WebSocket which adapter to load; this can be either thin, rainbows or goliath. If one of these servers is already loaded before faye/websocket is loaded, it will load appropriate adapters automatically.

# config.ru
require './app'
Faye::WebSocket.load_adapter('thin')
run App

Running the app with Thin

Thin can be started via the command line if you've set up a config.ru file for your application:

thin start -R config.ru -p 9292

Or, you can use rackup. In development mode, this adds middlewares that don't work with async apps, so you must start it in production mode:

rackup config.ru -s thin -E production -p 9292

It can also be started using the Rack::Handler interface common to many Ruby servers. It must be run using EventMachine, and you can configure Thin further in a block passed to run:

require 'eventmachine'
require 'rack'
require 'thin'
require './app'

EM.run {
  thin = Rack::Handler.get('thin')

  thin.run(App, :Port => 9292) do |server|
    # You can set options on the server here, for example to set up SSL:
    server.ssl_options = {
      :private_key_file => 'path/to/ssl.key',
      :cert_chain_file  => 'path/to/ssl.crt'
    }
    server.ssl = true
  end
}

Running the app with Rainbows

Faye::WebSocket can only be run using EventMachine. To begin with, you'll need a Rainbows config file that tells it to use EventMachine, along with whatever Rainbows/Unicorn configuration you require.

# rainbows.conf
Rainbows! do
  use :EventMachine
end

You can then run your config.ru file from the command line. Again, Rack::Lint will complain unless you put the application in production mode.

rainbows config.ru -c path/to/rainbows.conf -E production -p 9292

Rainbows also has a Ruby API for starting a server:

require 'rainbows'
require './app'

rackup = Unicorn::Configurator::RACKUP
rackup[:port] = 9292
rackup[:set_listener] = true
options = rackup[:options]
options[:config_file] = 'path/to/rainbows.conf'

server = Rainbows::HttpServer.new(App, options)

# This is non-blocking; use server.start.join to block
server.start

Running the app with Goliath

Goliath can be made to run arbitrary Rack apps by delegating to them from a Goliath::API instance. A simple server looks like this:

require 'goliath'
require './app'

class EchoServer < Goliath::API
  def response(env)
    App.call(env)
  end
end

Faye::WebSocket can also be used inline within a Goliath app:

require 'goliath'
require 'faye/websocket'

class EchoServer < Goliath::API
  def response(env)
    ws = Faye::WebSocket.new(env)

    ws.onmessage = lambda do |event|
      ws.send(event.data)
    end

    ws.rack_response
  end
end

Using the WebSocket client

The client supports both the plain-text ws protocol and the encrypted wss protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as hybi-13, though it's compatible with servers speaking later versions of the protocol.

require 'faye/websocket'
require 'eventmachine'

EM.run {
  ws = Faye::WebSocket::Client.new('ws://www.example.com/')

  ws.onopen = lambda do |event|
    p [:open]
    ws.send('Hello, world!')
  end

  ws.onmessage = lambda do |event|
    p [:message, event.data]
  end

  ws.onclose = lambda do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end
}

Subprotocol negotiation

The WebSocket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket:

ws = Faye::WebSocket::Client.new('ws://www.example.com/', ['irc', 'amqp'])

On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments:

ws = Faye::WebSocket.new(env, ['irc', 'amqp'])

If the client and server agree on a protocol, both the client- and server-side socket objects expose the selected protocol through the ws.protocol property. If they cannot agree on a protocol to use, the client closes the connection.

WebSocket API

The WebSocket API consists of several event handlers and a method for sending messages.

  • onopen fires when the socket connection is established. Event has no attributes.

  • onerror fires when the connection attempt fails. Event has no attributes.

  • onmessage fires when the socket receives a message. Event has one attribute, data, which is either a String (for text frames) or an Array of byte-sized integers (for binary frames).

  • onclose fires when either the client or the server closes the connection. Event has two optional attributes, code and reason, that expose the status code and message sent by the peer that closed the connection.

  • send(message) accepts either a String or an Array of byte-sized integers and sends a text or binary message over the connection to the other peer.

  • close(code, reason) closes the connection, sending the given status code and reason text, both of which are optional.

  • protocol is a string (which may be empty) identifying the subprotocol the socket is using.

License

(The MIT License)

Copyright © 2009-2011 James Coglan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Something went wrong with that request. Please try again.