class Crimson::Server

Attributes

clients[R]

Public Class Methods

new() click to toggle source
# File lib/crimson/server.rb, line 12
def initialize
  @clients = {}
end
template_html_path() click to toggle source
# File lib/crimson/server.rb, line 24
def self.template_html_path
  File.expand_path("#{__dir__}/../html/template.html")
end

Public Instance Methods

call(env) click to toggle source
# File lib/crimson/server.rb, line 35
def call(env)
  call_async(env) or call_faye(env) or serve_template(env)
end
call_async(env) click to toggle source
# File lib/crimson/server.rb, line 39
def call_async(env)
  Async::WebSocket::Adapters::Rack.open(env, protocols: ['ws']) do |connection|
      id = :"client_#{Utilities.generate_id}"
      client = Client.new(id, connection)
      clients[connection] = client
      
      @on_connect&.call(client)

    begin
      while message = connection.read
        client.on_message(message)
      end
    rescue Protocol::WebSocket::ClosedError
    ensure
      @on_disconnect&.call(client)
      clients.delete(connection)
    end
  end
end
call_faye(env) click to toggle source
# File lib/crimson/server.rb, line 59
def call_faye(env)
  if Faye::WebSocket.websocket?(env)
    connection = Crimson::Adapters::Faye.new(Faye::WebSocket.new(env))
    id = :"client_#{Utilities.generate_id}"
    client = Client.new(id, connection)
    clients[id] = client

    @on_connect&.call(client)

    connection.on :message do |event|
      client.on_message(JSON.parse(event.data))
    end

    connection.on :close do |event|
      @on_disconnect&.call(client)
      clients.delete(id)
      connection = nil
    end

    return connection.rack_response
  end
end
content(port, path = Server.template_html_path) click to toggle source
# File lib/crimson/server.rb, line 28
def content(port, path = Server.template_html_path)
  template = File.read(path)
  template.sub!("{PORT}", port)

  [template]
end
on_connect(&block) click to toggle source
# File lib/crimson/server.rb, line 16
def on_connect(&block)
  @on_connect = block if block_given?
end
on_disconnect(&block) click to toggle source
# File lib/crimson/server.rb, line 20
def on_disconnect(&block)
  @on_disconnect = block if block_given?
end
serve_template(env) click to toggle source
# File lib/crimson/server.rb, line 82
def serve_template(env)
  if env['REQUEST_PATH'] != '/'
    return Rack::Directory.new(File.expand_path("#{__dir__}/..")).call(env)
  else
    return [200, {"Content-Type" => "text/html"}, content(env['SERVER_PORT'])]
  end
end