class Socket2me::WsServer

Public Class Methods

new() click to toggle source

initializes an empty client list

# File lib/socket2me/ws_server.rb, line 11
def initialize
  @clients = []
end

Public Instance Methods

log(text) click to toggle source
# File lib/socket2me/ws_server.rb, line 34
def log(text)
  Socket2me.config.logger.debug "[WsServer] #{text}"
end
send_to_clients(msg) click to toggle source

sends a message to all connected clients @param [String] msg to send to all the clients

# File lib/socket2me/ws_server.rb, line 26
def send_to_clients(msg)
  EM.schedule do
    @clients.each do |socket|
      socket.send msg
    end
  end
end
start() click to toggle source

Start the EM::WebSocket thread. The server

# File lib/socket2me/ws_server.rb, line 40
def start
  @thread = Thread.new do
    EM::WebSocket.start(ws_options) do |ws|
      ws.onopen do |handshake|
        log "onopen: #{handshake.headers}"
        @clients << ws
      end

      ws.onclose do |event|
        log "closed: #{event}"
        @clients.delete ws
      end

      ws.onmessage do |msg|
        log "received: #{msg}"
      end
    end
  end
end
ws_options() click to toggle source

maps `Socket2me#config` options to `EM::WebSocket` options @return [Hash] hash of options compatible with EM::WebSocket#start

# File lib/socket2me/ws_server.rb, line 17
def ws_options
  {
    host: Socket2me.config.ws_host,
    port: Socket2me.config.ws_port
  }
end