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

Connection Management and Multithreading

Tony Arcieri edited this page Jul 18, 2015 · 1 revision

By default Reel handles the entire lifecycle of a connection for you:

Reel::Server::HTTP.run('127.0.0.1', 3000) do |connection|
  # BUT WHAT HAPPENS IF IT EXPLODES???
  connection.each_request do |request|
    request.respond :ok, "hello, world!"
  end
end

Reel will automatically detect when connections snap shut or otherwise have I/O errors and terminate them for you. It also will ordinarily close the connection sockets automatically, meaning there's no need to manually call #close on a Reel::Connection since Reel::Server will take care of that for you.

By default Reel is single-threaded. However, one of the great things Celluloid and Celluloid::IO afford you is the ability to easily leverage threads. To turn Reel into a multithreaded web server, we need to hand off the incoming connection to another thread or Celluloid actor.

All we need to do to turn Reel into a multithreaded web server is call the #detach method on a Reel::Connection and create a new actor to handle the connection after that.

class MyConnectionHandler
  include Celluloid

  def initialize(connection)
    @connection = connection
    async.run
  rescue Reel::SocketError
    @connection.close
  end

  def run
    @connection.each_request { |req| handle_request(req) }
  end

  def handle_request(request)
    ...
  end
end

Reel::Server::HTTP.run('127.0.0.1', 3000) do |connection|
  # We're handing this connection off to another actor, so
  # we detach it first before handing it off
  connection.detach

  MyConnectionHandler.new(connection)
end
Clone this wiki locally