Class: Staticme::WebSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/staticme/web_socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ WebSocket

Returns a new instance of WebSocket.



11
12
13
14
# File 'lib/staticme/web_socket.rb', line 11

def initialize(params)
  self.params = params
  @pool = []
end

Instance Attribute Details

#paramsObject

Returns the value of attribute params.



9
10
11
# File 'lib/staticme/web_socket.rb', line 9

def params
  @params
end

Instance Method Details

#emit(event) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/staticme/web_socket.rb', line 29

def emit(event)
  Staticme.logger.debug("Broadcasting event: #{event.to_json}")
  @pool.each do |ws|
    next if ws.nil?
    ws.send event.to_json
  end
end

#run!(&block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/staticme/web_socket.rb', line 16

def run!(&block)
  EM.next_tick do
    Staticme.logger.debug "Starting WebSocket server on ws://#{params[:host]}:#{params[:ws_port]}"
    EM::WebSocket.run(:host => params[:host], :port => params[:ws_port]) do |ws|
      @pool.push ws
      ws.onclose do
        @pool.delete ws
      end
    end
    block.call if block_given?
  end
end

#stop!Object



37
38
39
40
41
# File 'lib/staticme/web_socket.rb', line 37

def stop!
  Staticme.logger.debug('Stopping WebSocket server')
  EM.stop!
  @pool = []
end