Class: Domotics::Core::WsServer

Inherits:
Object
  • Object
show all
Defined in:
lib/domotics/core/ws_server.rb

Constant Summary collapse

@@parent =
nil

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ WsServer

Returns a new instance of WsServer.



4
5
6
7
8
# File 'lib/domotics/core/ws_server.rb', line 4

def initialize(args = {})
  @logger = Domotics::Core::Setup.logger || Logger.new(STDERR)
  @args = args
  @@parent, @child = Socket.pair(:UNIX, :DGRAM, 0)
end

Class Method Details

.publish(msg) ⇒ Object



30
31
32
# File 'lib/domotics/core/ws_server.rb', line 30

def self.publish(msg)
  @@parent.send msg, 0 if @@parent
end

Instance Method Details

#runObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/domotics/core/ws_server.rb', line 9

def run
  @logger.info { "[WebSocket] server [#{@args[:host]}:#{@args[:port]}]" }
  fork do
    @@parent.close
    channel = EventMachine::Channel.new
    Thread.new { loop { channel.push @child.recv(2**10) }}
    EventMachine::WebSocket.start(@args) do |ws|
      ws.onopen do
        sid = channel.subscribe { |msg| ws.send msg }
        @logger.info { "[WebSocket] client [#{sid}]" }
        ws.onmessage do |msg|
          @logger.info { "[WebSocket] message [#{msg}] from [#{sid}]" }
        end
        ws.onclose do
          channel.unsubscribe(sid)
        end
      end
    end
  end
  @child.close
end