Module: Bluecap::Server

Defined in:
lib/bluecap/server.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.handlersObject

Returns a Hash of handlers, creating a new empty hash if none have previously been set.



8
9
10
11
12
13
14
15
# File 'lib/bluecap/server.rb', line 8

def self.handlers
  @handlers ||= {
    attributes: Bluecap::Attributes,
    event: Bluecap::Event,
    identify: Bluecap::Identify,
    report: Bluecap::Report
  }
end

.handlers=(handlers) ⇒ Object

Assign handlers to respond to new data.

handlers - A Hash of lookup keys to handler classes.

Examples

handlers = {
  event: Bluecap::Event,
  identify: Bluecap::Identify
}

Returns nothing.



29
30
31
# File 'lib/bluecap/server.rb', line 29

def self.handlers=(handlers)
  @handlers = handlers
end

.runObject

Starts a TCP server running on the EventMachine loop.

Returns nothing.



64
65
66
67
68
69
# File 'lib/bluecap/server.rb', line 64

def self.run
  EventMachine::run do
    EventMachine::start_server(Bluecap.host, Bluecap.port, Bluecap::Server)
    Bluecap.log "Server started on #{Bluecap.host}:#{Bluecap.port}"
  end
end

Instance Method Details

#process(message) ⇒ Object



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

def process(message)
  klass = Bluecap::Server.handlers.fetch(message.recipient, Bluecap::NullHandler)
  port, ip_address = Socket.unpack_sockaddr_in(get_peername)
  Bluecap.log "Message received for #{message.recipient} handler from #{ip_address}:#{port}"
  handler = klass.new(message.contents)
  handler.handle
end

#receive_data(data) ⇒ Object

Process a message received from a client, sending a response if necessary.

data - The String containing JSON received from the client.

Examples

receive_data('{"identify": "Andy"}')

Returns nothing.



51
52
53
54
55
56
57
58
59
# File 'lib/bluecap/server.rb', line 51

def receive_data(data)
  begin
    message = Bluecap::Message.new(data)
    response = process(message)
    send_data(response) if response
  rescue Exception => e
    Bluecap.log e
  end
end