class WebSocketHelper

Attributes

latency[RW]

Public Class Methods

new(ws) click to toggle source
# File lib/sinatra/liveviews/json-websocket.rb, line 17
def initialize(ws)
        self.latency = nil
        # the sockets list is the list of all other WebSocketHelper classes
        # for all other connections. This makes it easy to send a message to
        # all connected clients
        @sockets = SharedList.list
        @ws = ws

        @ws.onopen { self.on_open }
        @ws.onclose { self.on_close }
        @ws.onmessage { |msg|
                d = JSON.parse(msg, {:symbolize_names => true})
                if d != nil && d[:event] != nil
                        Thread.new { self.on_message(d[:event], d[:data]) }
                end
         }
end

Public Instance Methods

on_close() click to toggle source
# File lib/sinatra/liveviews/json-websocket.rb, line 56
def on_close
        @sockets.delete(self)
end
on_message(event, data) click to toggle source
# File lib/sinatra/liveviews/json-websocket.rb, line 39
def on_message(event, data)
        event_method = 'on_' + event.underscore
        
        begin
                simulate_latency if !self.latency.nil?
                method(event_method).call(data) if self.respond_to? event_method
        rescue => e
                # if the subclass has defined an error handler, then use that if something has
                # happened, otherwise we just rethrow it
                if self.respond_to? 'handle_error'
                        handle_error(e, event_method, data)
                else
                        raise
                end
        end
end
on_open() click to toggle source
# File lib/sinatra/liveviews/json-websocket.rb, line 35
def on_open
        @sockets.push self
end
send(event, data = {}) click to toggle source

send a message in to the current client

# File lib/sinatra/liveviews/json-websocket.rb, line 61
def send(event, data = {})
        @ws.send({:event => event, :data => data}.to_json)
end
send_all(event, data) click to toggle source

sends a message to all connected clients, including the current client

# File lib/sinatra/liveviews/json-websocket.rb, line 66
def send_all(event, data)
        EM.next_tick {
                @sockets.each do |s|
                        s.send(event, data) 
                end
        }
end
send_others(event, data) click to toggle source

sends a message to all connected clients, except the current one

# File lib/sinatra/liveviews/json-websocket.rb, line 75
def send_others(event, data)
        EM.next_tick {
                @sockets.each do |s|
                        s.send(event, data) if s != self
                end
        }
end
simulate_latency() click to toggle source
# File lib/sinatra/liveviews/json-websocket.rb, line 83
def simulate_latency
        return if self.latency.nil?
        factor = ((rand() * 0.2 - 0.1) + 1) # 0.9 to 1.1
        delay = self.latency * factor
        sleep delay
end