Class: Sock::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/sock/server.rb

Overview

server provides a EM process that will manage websocket connections

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name: DEFAULT_NAME, logger: Logger.new(STDOUT), socket_params: { host: HOST, port: PORT }, mode: 'default') ⇒ Server

Returns a new instance of Server.



5
6
7
8
9
10
11
12
13
14
# File 'lib/sock/server.rb', line 5

def initialize(name: DEFAULT_NAME,
               logger: Logger.new(STDOUT),
               socket_params: { host: HOST, port: PORT },
               mode: 'default')
  @name = name
  @socket_params = socket_params
  @channels = {}
  @logger = logger
  @mode = mode
end

Instance Attribute Details

#channelsObject (readonly)

Returns the value of attribute channels.



4
5
6
# File 'lib/sock/server.rb', line 4

def channels
  @channels
end

#loggerObject (readonly)

Returns the value of attribute logger.



4
5
6
# File 'lib/sock/server.rb', line 4

def logger
  @logger
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/sock/server.rb', line 4

def name
  @name
end

Instance Method Details

#channel(channel_name) ⇒ Object

channel will find or create a EM channel. channels can have new events pushed on them or subscribe to events from them.



36
37
38
39
# File 'lib/sock/server.rb', line 36

def channel(channel_name)
  @logger.info "creating channel #{channel_name}" unless @channels[channel_name]
  @channels[channel_name] ||= EM::Channel.new
end

#socket_start_listeningObject

starts the websocket server on open this server will find a new channel based on the path on message it will fire an event to the default ‘incoming-hook’ channel. on close, we do nothing. (future direction: would be nice to unsubscribe the websocket event if we know it is the only one listening to that channel)



46
47
48
49
50
51
52
# File 'lib/sock/server.rb', line 46

def socket_start_listening
  EventMachine::WebSocket.start(@socket_params) do |ws|
    handle_open(ws)
    handle_message(ws)
    handle_close(ws)
  end
end

#start!Object

utility method used to subscribe on the default name and start the socket server



17
18
19
20
21
22
# File 'lib/sock/server.rb', line 17

def start!
  EM.run do
    subscribe(@name)
    socket_start_listening
  end
end

#subscribe(subscription) ⇒ Object

subscribe fires a event on a EM channel whenever a message is fired on a pattern matching



26
27
28
29
30
31
32
# File 'lib/sock/server.rb', line 26

def subscribe(subscription)
  @logger.info "Subscribing to: #{subscription + '*'}"
  pubsub.psubscribe(subscription + '*') do |chan, msg|
    @logger.info "pushing c: #{chan} msg: #{msg}"
    channel(chan).push(msg)
  end
end