class Hawkins::HttpAwareConnection

The LiveReload protocol requires the server to serve livereload.js over HTTP despite the fact that the protocol itself uses WebSockets. This custom connection class addresses the dual protocols that the server needs to understand.

Attributes

reload_body[R]
reload_size[R]

Public Class Methods

new(opts) click to toggle source
Calls superclass method
# File lib/hawkins/websockets.rb, line 12
def initialize(opts)
  em_opts = {}
  @ssl_enabled = opts['ssl_cert'] && opts['ssl_key']
  if @ssl_enabled
    em_opts[:tls_options] = {
      :private_key_file => Jekyll.sanitized_path(opts['source'], opts['ssl_key']),
      :cert_chain_file => Jekyll.sanitized_path(opts['source'], opts['ssl_cert']),
    }
    em_opts[:secure] = true
  end

  # Too noisy even for debug level logging.
  # em_opts[:debug] = true

  super(em_opts)

  reload_file = File.join(LIVERELOAD_DIR, "livereload.js")
  @reload_body = File.read(reload_file)
  @reload_size = @reload_body.bytesize
end

Public Instance Methods

dispatch(data) click to toggle source
Calls superclass method
# File lib/hawkins/websockets.rb, line 33
def dispatch(data)
  parser = Http::Parser.new
  parser << data

  # WebSockets requests will have a Connection: Upgrade header
  if parser.http_method != 'GET' || parser.upgrade?
    super
  elsif parser.request_url =~ /^\/livereload.js/
    headers = [
      'HTTP/1.1 200 OK',
      'Content-Type: application/javascript',
      "Content-Length: #{reload_size}",
      '',
      '',
    ].join("\r\n")
    send_data(headers)
    send_data(reload_body)
    close_connection_after_writing
  else
    body = "This port only serves livereload.js over HTTP.\n"
    headers = [
      'HTTP/1.1 400 Bad Request',
      'Content-Type: text/plain',
      "Content-Length: #{body.bytesize}",
      '',
      '',
    ].join("\r\n")
    send_data(headers)
    send_data(body)
    close_connection_after_writing
  end
end