Advertisement
  1. Code
  2. ActionScript

Введение в ByteArray

Scroll to top
Read Time: 11 min

() translation by (you can also view the original English article)

ByteArray чрезвычайно мощный класс, который может использоваться для многих вещей, связанных с данными, включая (но не ограничиваясь) сохранение данных игры в режиме онлайн, шифрование данных, сжатие данных и преобразование объекта BitmapData в файл PNG или JPG. В этом введении мы будем использовать класс ByteArray для того, чтобы принять нативный объект AS3 и закодировать его в строку, которая может быть сохранена на сервере для последующего восстановления, а затем декодирована позже.

В предыдущих руководствах мы видели, как использовать XML и JSON для кодирования данных в текстовом формате (String). Однако как XML, так и JSON предназначены для чтения человеком, и в результате они гораздо больше, чем это необходимо. Также может быть сложно преобразовать некоторые виды AS3 объекта в любой формат. ByteArray имеет некоторые действительно передовые функций, но чтобы начать с чего-то, мы просто рассмотрим один простой пример: который позволяет очень легко превратить AS3 объект в строку.


Конечный результат предварительного просмотра

Давайте взглянем на конечный результат, в направлении которого мы будем работать:

Когда вы вставить закодированную строку ByteArray в TextField и нажмите кнопку Load, она будет расшифрована и покажет свойства объекта, сохраненные в нем. Вы можете попробовать следующие закодированные ByteArrays; скопируйте и вставьте их в текстовое поле и нажмите на кнопку Load, чтобы увидеть о чем я говорю:

1
2
//This ByteArray will show my data (This is the default ByteArray loaded)
3
CgsBFW9jY3VwYXRpb24GB0NUTw93ZWJzaXRlBiFodHRwOi8vaWt0LmNvLmlkCW5hbWUGDVRhdWZpawE=
1
2
//This ByteArray will show my current thought
3
CgsBIWZvb2RfZm9yX3Rob3VnaHQGgnVJIGFtIHRoaW5raW5nIG9uIHNoYXJpbmcgdGhlIHRlY2huaXF1ZSBpIHVzZWQgdG8gbWFrZSBhIEZ1bGwgRmxhc2ggRHluYW1pYyBXZWJzaXRlIFNFTyBGcmllbmRseSBmb3IgbXkgbmV4dCBUdXRvcmlhbCBpbiBBY3RpdmVUdXRzKy4uLiA8dT5XaGF0IGRvIHlvdSB0aGluaz88L3U+IDxiPmlzIGl0IGEgZ29vZCBpZGVhPC9iPj8B
1
2
//This ByteArray will talk about Flash and SEO and my experience with them
3
CgsBEXF1ZXN0aW9uBoEDPGI+PHU+Q2FuIGEgZnVsbHkgZHluYW1pYyBGbGFzaCBXZWJzaXRlIGJlIFNFTyBmcmllbmRseTwvdT48L2I+Pz8NYW5zd2VyBoM/SXQgY2FuLCBoZXJlIGlzIHRoZSBwcm9vZiwgPGEgaHJlZj0naHR0cDovL3d3dy5nb29nbGUuY28uaWQvc2VhcmNoP3E9Zmxhc2grc2VvJmllPXV0Zi04Jm9lPXV0Zi04JmFxPXQnIHRhcmdldD0nX2JsYW5rJz5odHRwOi8vd3d3Lmdvb2dsZS5jby5pZC9zZWFyY2g/cT1mbGFzaCtzZW8maWU9dXRmLTgmb2U9dXRmLTgmYXE9dDwvYT4sIGlrdC5jby5pZCBpcyByYW5rZWQgIzYgb3ZlciB0aGVyZQE=

Шаг 1: Создание нового проекта ActionScript

Create New ActionScript ProjectCreate New ActionScript ProjectCreate New ActionScript Project

В окне «Flash Builder»:

  1. Откройте Flash Builder 4
  2. Нажмите на File Menu
  3. Наведите курсор на New
  4. Нажмите на проект ActionScript

Шаг 2: Настройка New ActonScript Project

ActionScript Project SetupActionScript Project SetupActionScript Project Setup

В окне «New Project ActionScript»:

  1. В поле Project name введите «TUTORIAL_ByteArray»
  2. Пожалуйста, запомните, где вы сохраняете проект
  3. Нажмите кнопку «Finish»

Шаг 3: Base64.as

Скопируйте Base64.as в каталог «com» вашего проекта.

Copy Base64.as file into 'com' directoryCopy Base64.as file into 'com' directoryCopy Base64.as file into 'com' directory
  1. Создайте новый каталог «com» внутри вашего каталога src.
  2. Скачайте файл Base64.as из источника загрузок.
  3. Поместите файл в созданную директорию «com».

Base64.as пригодится позже. Это по Steve Webster, который привык находиться в dynamicflash.com (он покинул Flash-сообществj пару лет назад).


Шаг 4: Необходимые классы

Import all Classes used in this projectImport all Classes used in this projectImport all Classes used in this project

В классе TUTORIAL_ByteArray (который является основным классом) пожалуйста импортируйте следующие классы для этого руководства:

1
2
package
3
{
4
  import flash.display.Sprite;
5
	import flash.text.TextField;
6
	import flash.text.TextFieldType;
7
	import flash.text.TextFieldAutoSize;
8
	import flash.text.TextFormat;
9
	import flash.events.MouseEvent;
10
	import flash.utils.ByteArray;
11
	import com.Base64;
12
	
13
	public class TUTORIAL_ByteArray extends Sprite
14
	{
15
		public function TUTORIAL_ByteArray()
16
		{
17
			
18
		}
19
	}
20
}

Шаг 5: Привыкаем к Flash Builder I

Trace the 'Hello World' messageTrace the 'Hello World' messageTrace the 'Hello World' message

Добавьте следующий код в конструктор TUTORIAL_ByteArray для очень простой проверки.

1
2
public function TUTORIAL_ByteArray()
3
{
4
	var _test:String = "Hello world!";
5
	trace(_test);
6
}

Нажмите клавишу F11 для запуска этого проекта, вы должны получить сообщение внутри окна консоли.


Шаг 6: Привыкаем к Flash Builder II

Local variable only available inside the function it is createdLocal variable only available inside the function it is createdLocal variable only available inside the function it is created

Теперь давайте попробуем проследить сообщение внутри переменной _test, но на этот раз мы будем делать это с другой функцией:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	var _test:String = "Hello world!";
5
	TestFunction();
6
}
7
private function TestFunction():void{
8
	trace(_test);
9
}

Нажмите сочетание клавиш CTRL + S, чтобы сохранить проект. Ошибка обнаружена после того, как вы сохранили ваш проект; это потому, что переменная, которая объявлена внутри функции не будут доступна для любой другой функции. Так что в этом случае, мы должны объявить переменную _test снаружи:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	TestFunction();
5
}
6
private function TestFunction():void{
7
	trace(_test);
8
}
9
private var _test:String = "Hello world!";
Private variables are available to all function inside the same classPrivate variables are available to all function inside the same classPrivate variables are available to all function inside the same class

Шаг 7: Необходимые приватные переменные

Create all private variables for this projectCreate all private variables for this projectCreate all private variables for this project

Пожалуйста, добавьте следующие приватные переменные для этого проекта:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	TestFunction();
5
}
6
private function TestFunction():void{
7
	trace(_test);
8
}
9
private var _test:String = "Hello World!";
10
private var _loadButton:TextField;
11
private var _inputField:TextField;
12
private var _testObject:Object;
13
private var _testByteArray:ByteArray;

Шаг 8: UI

Давайте создадим простой пользовательский интерфейс для этого проекта.

a Simple user interfacea Simple user interfacea Simple user interface

Теперь, когда нам нужно отображать что-то в наш проект, мы должны объявить нашей сцене размеры (проверьте строку 13).

Переименуйте нашу TestFunction в функцию InitUI и поместите следующую строку кода внутри. Пожалуйста, прочитайте закомментированные объяснения внутри кода.

1
2
[SWF(width="550", height="400", frameRate="60", pageTitle="Tutorial ByteArray")]
3
public class TUTORIAL_ByteArray extends Sprite
4
{
5
	public function TUTORIAL_ByteArray()
6
	{
7
		InitUI();
8
	}
9
	private function InitUI():void{
10
		//Initialize our TextFields so that we can use them

11
		_loadButton = new TextField();
12
		_inputField = new TextField();
13
		
14
		//Give a defaultTextFormat for both of them (Tahoma at 11pt, colored 0x777777)

15
		_loadButton.defaultTextFormat = _inputField.defaultTextFormat = new TextFormat("Tahoma", 11, 0x777777);
16
		
17
		//Give both of them a border 

18
		_loadButton.border = _inputField.border = true;
19
		
20
		//Set the autosize for our Load Button , so that it will automatically shrink / grow to fit the text inside

21
		_loadButton.autoSize = TextFieldAutoSize.LEFT;
22
		
23
		//Set the selectable of our Load Button to false, so that user cannot select the text in it

24
		_loadButton.selectable = false;
25
		
26
		//Set the multiline and wordWrap of our Input Field to true, so that a long text will automatically wrapped to the next line

27
		_inputField.multiline = _inputField.wordWrap = true;
28
		
29
		//Enable user to type something into our Input Field, by setting this type property 

30
		_inputField.type = TextFieldType.INPUT;
31
		
32
		//Put some text into Both of them

33
		_loadButton.text = "Load";
34
		_inputField.text = "";
35
		
36
		//Add both of them into stage, so that they are visible to our visitors

37
		addChild(_inputField);
38
		addChild(_loadButton);
39
		
40
		//Position our Input Field and make it bigger 

41
		_inputField.x = 25;
42
		_inputField.y = 25;
43
		_inputField.width = 200;
44
		_inputField.height = 150;
45
		
46
		//There is a reason why i did this, so that the Load Button is located directly below our Input Field

47
		//So you can position the Input Field anywhere you like, as long as there is this code, the Load Button will stick below the Input Field

48
		_loadButton.y = _inputField.y + _inputField.height;
49
		_loadButton.x = _inputField.x;
50
	}

Нажмите клавишу F11, чтобы запустить этот проект и увидеть простой пользовательский интерфейс, который мы создали.


Шаг 9: Добавление интерактивности

Type into the field and click the load buttonType into the field and click the load buttonType into the field and click the load button

Пожалуйста, прочитайте  закомментированные объяснения внутри кода

1
2
	_loadButton.y = _inputField.y + _inputField.height;
3
	_loadButton.x = _inputField.x;
4
	
5
	//Add an Event Listener for our _loadButton, so whenever the user clicks this button, 

6
	//Flash will call _loadButton_CLICK() Method

7
	_loadButton.addEventListener(MouseEvent.CLICK, _loadButton_CLICK, false, 0, true);
8
}
9
//This method will be called whenever user click the _loadButton

10
private function _loadButton_CLICK(Events:MouseEvent = null):void{
11
	//Get anything that the user input and save them into our _test variable

12
	_test = _inputField.text;
13
	
14
	//Trace the _test variable

15
	trace("User input the following message : " + _test);
16
}

Нажмите клавишу F11, чтобы запустить этот проект; Попробуйте ввести что-то в _inputField, а затем нажмите _loadButton. Это самая базовая техника получения переменной от нашего пользователя и хранение ее в нашей приватной переменной.


Пища для размышлений

Мы, наконец, достигли наших наиболее важных шагов в рамках этого проекта, но прежде чем мы продолжим, позвольте мне обеспечить умственный стимулом для размышления. В настоящее время в нашем проекте, мы способны получить String и хранить ее в нашей приватной переменной. Но это только строка; как насчет если пользователь захочет ввести что-то внутри _inputFieldтак,  что я могу получить Object из него? Что следует пользователю напечатать? Ответ является «В кодировке Base64 ByteArray»


Шаг 10: Введение в ByteArray

Output from our ByteArrayOutput from our ByteArrayOutput from our ByteArray

Мы будем действовать медленно на этот раз, так что вы поймете класс ByteArray и будете иметь возможность делать собственные манипуляции с данными и применять их в ваших собственных проектах. Пожалуйста, прочитайте закомментированные объяснения внутри кода:

1
2
public function TUTORIAL_ByteArray()
3
{
4
	InitUI();
5
	CreateByteArray();
6
}
7
private function CreateByteArray():void{
8
	//Initialize our _testObject variable, so that we can populate many dynamic properties and store String data in it (we will load them later whenever user clicked the _loadButton)

9
	_testObject = new Object();
10
	_testObject.name = "Taufik";
11
	_testObject.website = "<a href='https://ikt.co.id'>http://ikt.co.id</a>";
12
	_testObject.occupation = "CTO";
13
	
14
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

15
	_testByteArray = new ByteArray();
16
	
17
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

18
	_testByteArray.writeObject(_testObject);
19
	
20
	//Lets see if everything works properly

21
	trace("Our first ByteArray created :: " + _testByteArray.toString());
22
}

Нажмите клавишу F11, чтобы запустить этот проект. Смотрите, как это просто, ByteArray представляет собой чрезвычайно мощный класс и все это все еще не так сложно. Мы взяли нативный объект AS3 и превратили его в Action Message Format.

Перед отправкой данных в PHP-скрипт, с помощью метода GET, мы должны преобразовать его в строку Base64. Это потому, что Base64 может передаваться через XML (и HTML).


Шаг 11: Кодирование ByteArray в строку Base64

a Base64 String representation of our Byte dataa Base64 String representation of our Byte dataa Base64 String representation of our Byte data

Пожалуйста, прочитайте закомментированные объяснение в коде.

1
2
private function CreateByteArray():void{
3
	//Initialize our _testObject variable, so that we can populate many dynamic properties and store String data in it 

4
	//(we will load them later whenever user clicks the _loadButton)

5
	_testObject = new Object();
6
	_testObject.name = "Taufik";
7
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
8
	_testObject.occupation = "CTO";
9
	
10
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

11
	_testByteArray = new ByteArray();
12
	
13
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

14
	_testByteArray.writeObject(_testObject);
15
	
16
	//Encode the ByteArray into Base64 String (so that we can send them via PHP or copy the text to notepad), again IT IS VERY SIMPLE!

17
	var encoded:String = Base64.encodeByteArray(_testByteArray);
18
	
19
	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)

20
	_inputField.text = encoded;
21
}

Нажмите клавишу F11, чтобы запустить этот проект. Преобразование объекта в ByteArray простое, преобразование Byte значения наших данных в строку Base64 является также простым, все благодаря Base64.as.


Шаг 12: Преобразование кодированной строки Base64 в объект

Converting a Base64 String into Object and displaying its properties and valuesConverting a Base64 String into Object and displaying its properties and valuesConverting a Base64 String into Object and displaying its properties and values

Мы будем стараться декодировать введенные строки Base64 в объект всякий раз, когда пользователь кликает _loadButton, измените нашу функцию _loadButton_CLICK. Пожалуйста, прочитайте закомментированные объяснение внутри кода:

1
2
private function _loadButton_CLICK(Events:MouseEvent = null):void{
3
	//We have to catch any Errors

4
	try{
5
		//We decode our encoded Base64 String into a ByteArray, so that we can retrieve our Object back

6
		var DecodedByteArray:ByteArray = Base64.decodeToByteArray(_inputField.text);
7
		
8
		//If converting an Object into ByteArray is simple, retrieving an Object from ByteArray is as simple as this

9
		var LoadedObject:Object = DecodedByteArray.readObject();
10
		
11
		//Prepare to output all properties and their values inside the LoadedObject

12
		var Output:String = "";
13
		for (var VarName:String in LoadedObject){
14
			Output += VarName + " : " + LoadedObject[VarName] + "<br>";
15
		} 
16
		
17
		//Output them into our _inputField 

18
		_inputField.htmlText = Output;
19
	}catch(err:Error){
20
		_inputField.text = "Please input an Encoded ByteArray into this TextField before clicking the 'Load' Button. Error message :: " + err.message;
21
	}
22
}

Нажмите клавишу F11, чтобы запустить этот проект. Мы получаем нашу закодированную строку Base64 из нашего _testObject внутри нашего _inputField; Нажмите кнопку _loadButton, чтобы увидеть как наш проект преобразует эту строку Base64 обратно и отображает все свойства и значения. Вы можете попробовать скопировать и вставить строки Base64 в начале этого руководства и читать все мои сообщения.


Заключение

Класс ByteArray чрезвычайно мощный, и все же он очень простой в использовании. Я видел много отличных Flash-приложений и там используют ByteArray для выполнения столь многих выносящих мозг манипуляций данными, например таких, которые я упомянул в начале этого руководства. Я слышал, многие программисты Flash игр используют XML для сохранения данных своих посетителей «сохранить данные игры», но как мы все уже знаем, XML чертовски сложный класс; с ByteArray, я могу сохранить что-то вроде этого ЛЕГКО.

1
2
private function CreateByteArray():void{
3
	_testObject = new Object();
4
	_testObject.name = "Taufik";
5
	_testObject.website = "<a href='http://ikt.co.id'>http://ikt.co.id</a>";
6
	_testObject.occupation = "CTO";
7
	_testObject.level = 99;
8
	
9
	//Get the state of this Game Character Inventory

10
	var _inventory:Array = new Array({item_id:5, amount:1}, {item_id:85, amount:1}, {item_id:42, amount:5});
11
	_testObject.inventory = _inventory;
12
	
13
	//Get what is the skill they already level up

14
	var _skill:Array = new Array({skill_id:1, level:0}, {skill_id:2, level:1});
15
	_testObject.skill = _skill;
16
	
17
	//Initialize our _byteArray variable, so that we can start converting object into a ByteArray

18
	_testByteArray = new ByteArray();
19
	
20
	//Convert the Object into Byte Array, This is how you do it, to convert an Object into a ByteArray, IT IS SIMPLE isnt it? :))

21
	_testByteArray.writeObject(_testObject);
22
	
23
	//Encode the ByteArray into Base64 String (so that we can send them via PHP or copy the text to notepad), again IT IS VERY SIMPLE!

24
	var encoded:String = Base64.encodeByteArray(_testByteArray);
25
	
26
	//Put the encoded Base64 String into our _inputField (so that we can copy them into notepad)

27
	_inputField.text = encoded;
28
}

Да, все сложности  занимают только пару строчек кода, представьте себе ужас сохранения этих данных с помощью XML и извлечения их обратно для дальнейшего использования. Все что я должен сказать, с Byte данными вы можете достичь много вещей, и некоторые могут быть решением, которое вы так долго искали все это время.

Я надеюсь, что вы нашли это руководство полезным. Спасибо за чтение!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.