class WebSocket::Driver::Hybi

def emit_frame(buffer)

def emit_frame(buffer)
  frame    = @frame
  opcode   = frame.opcode
  payload  = frame.payload = Mask.mask(buffer, @frame.masking_key)
  bytesize = payload.bytesize
  @frame = nil
  case opcode
    when OPCODES[:continuation] then
      return fail(:protocol_error, 'Received unexpected continuation frame') unless @message
      @message << frame
    when OPCODES[:text], OPCODES[:binary] then
      @message = Message.new
      @message << frame
    when OPCODES[:close] then
      code, reason = payload.unpack('S>a*') if bytesize >= 2
      reason = Driver.encode(reason || '', Encoding::UTF_8)
      unless (bytesize == 0) or
             (code && code >= MIN_RESERVED_ERROR && code <= MAX_RESERVED_ERROR) or
             ERROR_CODES.include?(code)
        code = ERRORS[:protocol_error]
      end
      if bytesize > 125 or !reason.valid_encoding?
        code = ERRORS[:protocol_error]
      end
      shutdown(code || DEFAULT_ERROR_CODE, reason || '')
    when OPCODES[:ping] then
      frame(payload, :pong)
      emit(:ping, PingEvent.new(payload))
    when OPCODES[:pong] then
      message = Driver.encode(payload, Encoding::UTF_8)
      callback = @ping_callbacks[message]
      @ping_callbacks.delete(message)
      callback.call if callback
      emit(:pong, PongEvent.new(payload))
  end
  emit_message if frame.final and MESSAGE_OPCODES.include?(opcode)
end