Skip to content
This repository has been archived by the owner on Dec 7, 2018. It is now read-only.

WebSockets

Paweł Urbanek edited this page May 30, 2014 · 12 revisions

See also: Reel::WebSocket Yardoc

Using Reel's native WebSockets API

Reel has native support for WebSockets through the Reel::WebSocket class. You can obtain one of these objects by calling the #websocket method on a Reel::Request. This will hijack the socket from the underlying Reel::Connection. Here's how it's done:

require "reel"

Reel::Server::HTTP.run("0.0.0.0", 3000) do |connection|
  connection.each_request do |request|
    # WebSocket support
    if request.websocket?
      puts "Client made a WebSocket request to: #{request.url}"
      websocket = request.websocket

      websocket << "Hello everyone out there in WebSocket land"
      websocket.close
    else
      puts "Client requested: #{request.method} #{request.url}"
      request.respond :ok, "Hello, world!"
    end
  end
end

For a more comprehensive example, please check out the examples/websockets.rb example in Reel's "examples" directory.

Using Webmachine

The Reel adapter for Webmachine allows you to set a handler proc for incoming Websockets connections. Use the following syntax when configuring your application:

app.configure do |config|
  # Handler for incoming websockets
  config.adapter_options[:websocket_handler] = proc do |websocket|
    # websocket is a Reel::WebSocket
    websocket << "hello, world"
  end
end
Clone this wiki locally