Class: Socket2me::WsServer

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/socket2me/ws_server.rb

Instance Method Summary collapse

Constructor Details

#initializeWsServer

initializes an empty client list



11
12
13
# File 'lib/socket2me/ws_server.rb', line 11

def initialize
  @clients = []
end

Instance Method Details

#log(text) ⇒ Object



34
35
36
# File 'lib/socket2me/ws_server.rb', line 34

def log(text)
  Socket2me.config.logger.debug "[WsServer] #{text}"
end

#send_to_clients(msg) ⇒ Object

sends a message to all connected clients

Parameters:

  • msg (String)

    to send to all the clients



26
27
28
29
30
31
32
# 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

#startObject

Start the EM::WebSocket thread. The server



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 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_optionsHash

maps ‘Socket2me#config` options to `EM::WebSocket` options

Returns:

  • (Hash)

    hash of options compatible with EM::WebSocket#start



17
18
19
20
21
22
# File 'lib/socket2me/ws_server.rb', line 17

def ws_options
  {
    host: Socket2me.config.ws_host,
    port: Socket2me.config.ws_port
  }
end