Class: Brief::Server::Socket

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Socket

Returns a new instance of Socket.



22
23
24
25
26
27
# File 'lib/brief/server/socket.rb', line 22

def initialize(options={})
  @options = options
  @gateway = gateway
  @host    = options.fetch(:host, '0.0.0.0')
  @port    = options.fetch(:port, 9099)
end

Instance Attribute Details

#gatewayObject (readonly)

Returns the value of attribute gateway.



17
18
19
# File 'lib/brief/server/socket.rb', line 17

def gateway
  @gateway
end

#hostObject (readonly)

Returns the value of attribute host.



17
18
19
# File 'lib/brief/server/socket.rb', line 17

def host
  @host
end

#optionsObject (readonly)

Returns the value of attribute options.



17
18
19
# File 'lib/brief/server/socket.rb', line 17

def options
  @options
end

#portObject (readonly)

Returns the value of attribute port.



17
18
19
# File 'lib/brief/server/socket.rb', line 17

def port
  @port
end

Class Method Details

.start(options = {}, &block) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/brief/server/socket.rb', line 2

def self.start(options={}, &block)
  require 'em-websocket' unless defined?(EM::WebSocket)

  host = options.fetch(:host, '0.0.0.0')
  host = options.fetch(:port, '8023')

  gateway = Brief::Server::Gateway.new(options)

  socket = new(gateway: gateway)

  EM.run {
    socket.start
  }
end

Instance Method Details

#log(message) ⇒ Object



29
30
31
32
33
# File 'lib/brief/server/socket.rb', line 29

def log(message)
  if options[:log_to_console]
    puts(message)
  end
end

#startObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/brief/server/socket.rb', line 35

def start
  log "Starting socket gateway: #{port} host: #{ host }"
  EM::WebSocket.run(:host => host, :port => port) do |ws|
    ws.onopen do |handshake|
      log("== Brief client connected")
      log(handshake.inspect)
    end

    ws.onclose do
      log("brief Connection closed")
    end

    ws.onmessage do |data|
       message = OpenStruct.new(JSON.parse(data))
       log "== Websocket Command: #{ message }"
    end
  end
end