Class: HighCarb::WSConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/highcarb/sockets.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(websocket, logger) ⇒ WSConnection

Returns a new instance of WSConnection.



17
18
19
20
21
22
23
24
25
# File 'lib/highcarb/sockets.rb', line 17

def initialize(websocket, logger)
  @logger = logger
  @client_id = (self.class.last_client_id += 1)

  @websocket = websocket
  websocket.onopen &method(:on_open)
  websocket.onclose &method(:on_close)
  websocket.onmessage &method(:on_msg)
end

Class Attribute Details

.connected_clientsObject

Returns the value of attribute connected_clients.



6
7
8
# File 'lib/highcarb/sockets.rb', line 6

def connected_clients
  @connected_clients
end

.last_client_idObject

Returns the value of attribute last_client_id.



7
8
9
# File 'lib/highcarb/sockets.rb', line 7

def last_client_id
  @last_client_id
end

Instance Attribute Details

#client_idObject (readonly)

Returns the value of attribute client_id.



13
14
15
# File 'lib/highcarb/sockets.rb', line 13

def client_id
  @client_id
end

#loggerObject (readonly)

Returns the value of attribute logger.



15
16
17
# File 'lib/highcarb/sockets.rb', line 15

def logger
  @logger
end

#websocketObject (readonly)

Returns the value of attribute websocket.



14
15
16
# File 'lib/highcarb/sockets.rb', line 14

def websocket
  @websocket
end

Instance Method Details

#on_closeObject



32
33
34
35
# File 'lib/highcarb/sockets.rb', line 32

def on_close
  logger.info { "[WS] Closed client: #{client_id}" }
  self.class.connected_clients.delete self
end

#on_msg(msg) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/highcarb/sockets.rb', line 37

def on_msg(msg)
  logger.info { "[WS] Message from #{client_id}: #{msg}" }

  self.class.connected_clients.each do |client|
    if client != self
      client.websocket.send msg
    end
  end
end

#on_openObject



27
28
29
30
# File 'lib/highcarb/sockets.rb', line 27

def on_open
  logger.info { "[WS] Open client: #{client_id}" }
  self.class.connected_clients << self
end