Sha256: fbe3041bebca2f279ef17b5e58d1938e501d2e6dc27e7e5c4248babadd2bdfb3

Contents?: true

Size: 877 Bytes

Versions: 4

Compression:

Stored size: 877 Bytes

Contents

require 'json'

class FlashConnection < EventMachine::Connection
  def initialize
    @buffer = ''
    
    set_comm_inactivity_timeout 60
  end
  # JSON packets
  def send_json json
    send_data json.to_json + "\0"
  end
  
  # Null-terminated lines
  def send_line line
    send_data line + "\0"
  end
  
  def receive_line line
    receive_json JSON.parse(line)
  rescue JSON::ParserError
    log "JSON parsing error"
  end
  
  # Raw bytes
  def receive_data data
    @buffer += data
    
    while @buffer.include? "\0"
      packet = @buffer[0, @buffer.index("\0")]
      @buffer = @buffer[(@buffer.index("\0")+1)..-1]
      
      receive_line packet
    end
  rescue => ex
    p ex, ex.backtrace
  end

  # TODO: redundant code
  def log text
    puts "#{self}: #{text}" if Rails.env != "production" || $DEBUG
  end
  
  def to_s
    "connection #{inspect}"
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
protolink-0.2.11 lib/protolink/flash_connection.rb
protolink-0.2.10 lib/protolink/flash_connection.rb
protolink-0.2.9 lib/protolink/flash_connection.rb
protolink-0.2.8 lib/protolink/flash_connection.rb