Class: Hawkins::HttpAwareConnection

Inherits:
EventMachine::WebSocket::Connection
  • Object
show all
Defined in:
lib/hawkins/websockets.rb

Overview

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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ HttpAwareConnection

Returns a new instance of HttpAwareConnection.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hawkins/websockets.rb', line 12

def initialize(opts)
  @ssl_enabled = opts['ssl_cert'] && opts['ssl_key']
  if @ssl_enabled
    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']),
    }
    opts[:secure] = true
  end
  super
  @reload_file = File.join(LIVERELOAD_DIR, "livereload.js")
end

Instance Attribute Details

#reload_fileObject (readonly)

Returns the value of attribute reload_file.



10
11
12
# File 'lib/hawkins/websockets.rb', line 10

def reload_file
  @reload_file
end

Instance Method Details

#dispatch(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hawkins/websockets.rb', line 25

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: #{File.size(reload_file)}",
      '',
      '',
    ].join("\r\n")
    send_data(headers)
    stream_file_data(reload_file).callback do
      close_connection_after_writing
    end
  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