応用編と言うことで、FlexとGoogle App Engine(Java)間でAMF通信する方法を
紹介したいと思います。
★クライアント(Flex)から、リクエストをAMF形式で送信する方法
var commandAmf:ByteArray = new ByteArray(); commandAmf.writeObject(command); var request:URLRequest = new URLRequest(COMMAND_URL); request.method = URLRequestMethod.POST; request.contentType = "application/x-amf"; request.data = commandAmf; var handler:EventHandler = new EventHandler(command, callback); var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, handler.completeHandler); loader.addEventListener(IOErrorEvent.IO_ERROR, handler.failHandler); loader.load(request);
- リクエストのパラメータを詰め込んだcommandを作成する(上記では省略)
- ByteArrayに、writeObjectを使ってAMF形式で書き出す
- GAEのURLを持った、URLRequestを作成し、データを設定する
- URLLoaderを作成し、load()使って、リクエストを送信する
★サーバ(GAE)で、AMFを解釈し、命令(Command)を実行する方法
protected void doPost(
HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Decode Parameter.
ICommand<?> command =
AmfUtil.decode(req.getInputStream(), ICommand.class);
// Command Execution.
Object data = command.execute();
// Result.
byte[] result = AmfUtil.encode(
new Result(data, Result.SUCCESS, null));
resp.setContentType("application/x-amf");
resp.setContentLength(result.length);
resp.getOutputStream().write(result);
}
- リクエストをICommandとしてDecodeする
(※ICommandとは、execute()メソッドのみを持つInterface) - ICommandをexecute()し、結果データを取得する。
- 結果データを、Result型に詰め込んで、AMFにEncodeして返す
★クライアント(Flex)で、リクエストの結果を取得する方法
public function completeHandler(event:Event):void {
var resultAmf:ByteArray = ByteArray(event.target.data);
var result:Result = resultAmf.readObject() as Result;
if (result == null) {
result = new Result(null, -2, "No Result.");
}
callback(this.command, result);
}
public function failHandler(event:IOErrorEvent):void {
var result:Result = new Result(null, -1, "Connection Error.");
callback(this.command, result);
}
- AMFデータを取得し、readObject()を使ってResultを取り出す
- Callbackファンクションを実行する
※以下に、サンプルコマンドや、例外処理なども追加した全サンプルソースを貼って置きますのでご利用ください。
AMF48-GAESample