Class: Puggernaut::Server::Websocket

Inherits:
Object
  • Object
show all
Includes:
Logger, Shared
Defined in:
lib/puggernaut/server/websocket.rb

Instance Method Summary collapse

Methods included from Shared

#gather_messages, #join_channels, #leave_channel, #query_defaults

Methods included from Logger

#logger, logger

Constructor Details

#initialize(host, port) ⇒ Websocket

Returns a new instance of Websocket.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/puggernaut/server/websocket.rb', line 8

def initialize(host, port)
  EventMachine::WebSocket.start(:host => host, :port => port) do |ws|
    ws.onopen do
      logger.info "Server::Websocket#initialize - Open"
      channel = nil
      join_leave = nil
      joined = nil
      subscription_id = nil
      ws.onmessage do |msg|
        logger.info "Server::Websocket#initialize - Message - #{msg}"
        channels, join_leave, lasts, time, user_id = query_defaults(CGI.parse(msg))
        channel ||= Channel.create(channels, user_id)
        if join_leave && user_id && !joined
          joined = true
          join_channels(channels, user_id)
        end
        messages = gather_messages(channels, lasts, time)
        unless messages.empty?
          ws.send messages
        else
          logger.info "Server::Websocket#initialize - Subscribed - #{channel.channels.join(", ")}"
          subscription_id = channel.subscribe { |str| ws.send str }
        end
      end
      ws.onclose do
        if subscription_id
          channel.unsubscribe(subscription_id)
          logger.info "Sever::Websocket#initialize - Unsubscribe - #{channel.channels.join(", ")}"
          if join_leave && channel.user_id
            leave_channel(channel)
          end
          Channel.channels.delete channel
        end
      end
    end
  end
end