Class: Crimson::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/crimson/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Server

Returns a new instance of Server.



13
14
15
16
# File 'lib/crimson/server.rb', line 13

def initialize(opts = {})
  @opts = opts || {}
  @clients = {}
end

Instance Attribute Details

#clientsObject (readonly)

Returns the value of attribute clients.



11
12
13
# File 'lib/crimson/server.rb', line 11

def clients
  @clients
end

Instance Method Details

#hostObject



18
19
20
# File 'lib/crimson/server.rb', line 18

def host
  @opts[:host] || '0.0.0.0'
end

#on_connect(&block) ⇒ Object



22
23
24
# File 'lib/crimson/server.rb', line 22

def on_connect(&block)
  @on_connect = block if block_given?
end

#on_disconnect(&block) ⇒ Object



26
27
28
# File 'lib/crimson/server.rb', line 26

def on_disconnect(&block)
  @on_disconnect = block if block_given?
end

#portObject



30
31
32
# File 'lib/crimson/server.rb', line 30

def port
  @opts[:port] || 10_000
end

#run(websocket_enabled: true, webserver_enabled: true) ⇒ Object



34
35
36
37
38
39
# File 'lib/crimson/server.rb', line 34

def run(websocket_enabled: true, webserver_enabled: true)
  EM.run do
    start_websocket if websocket_enabled
    start_webserver if webserver_enabled
  end
end

#start_webserverObject



41
42
43
44
45
46
# File 'lib/crimson/server.rb', line 41

def start_webserver
  template = File.read("#{__dir__}/../html/template.html")
  template.sub!("{PORT}", websocket_port.to_s)

  Thin::Server.start(WebServer.new(template), host, port, signals: false)
end

#start_websocketObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/crimson/server.rb', line 48

def start_websocket
  WebSocket::EventMachine::Server.start(host: host, port: websocket_port) do |ws|
    id = :"client_#{Utilities.generate_id}"
    client = Client.new(id, ws)

    ws.onopen {
      clients[id] = client
      @on_connect.call(client)
    }

    ws.onclose {
      @on_disconnect.call(client)
      clients.delete(id)
    }
  end
end

#websocket_portObject



65
66
67
# File 'lib/crimson/server.rb', line 65

def websocket_port
  port + 1
end