class DrunkMonkey::Transport::WebSocket

Public Class Methods

resume(request, options = {}) click to toggle source
Calls superclass method DrunkMonkey::Transport::Base::resume
# File lib/drunkmonkey/transport.rb, line 67
def self.resume request, options = {}
  websocket = super
  websocket.handle_connection request
end

Public Instance Methods

handle_connection(request) click to toggle source
# File lib/drunkmonkey/transport.rb, line 72
def handle_connection request
  handshake request
  @controller.async.fire :open, Actor.current
  loop do
    Celluloid.sleep 0.001
    upstream
    downstream
    return if @socket.closed?
  end
end
push(message) click to toggle source
# File lib/drunkmonkey/transport.rb, line 83
def push message
  @messages << message
end

Private Instance Methods

downstream() click to toggle source
# File lib/drunkmonkey/transport.rb, line 110
def downstream
  if message = @messages.shift
    @socket.write(
      ::WebSocket::Frame::Outgoing::Server.new(
        data: portal(message), type: :text, version: @handshake.version))
  end
rescue Errno::EPIPE => e  
end
handshake(request) click to toggle source
# File lib/drunkmonkey/transport.rb, line 88
def handshake request
  env = request.env
  raise HijackAPINotFoundError unless hijack = env["rack.hijack"]
  hijack.call
  @socket = env["rack.hijack_io"]
  @handshake = ::WebSocket::Handshake::Server.new
  @handshake.from_rack env
  @socket.write @handshake.to_s
end
upstream() click to toggle source
# File lib/drunkmonkey/transport.rb, line 98
def upstream
  buffer = ::WebSocket::Frame::Incoming::Server.new(version: @handshake.version)
  buffer << @socket.read_nonblock(1024) rescue nil
  while frame = buffer.next
    case frame.type
    when :text, :binary
      data = JSON.parse(frame.data)
      @controller.async.fire :message, Actor.current, data["data"]
    end
  end
end