I would like to introduce a advanced usage of AMF48.
Following is a way to connect from Flex to Google App Engine(Java) by AMF.
**Client(Flex): Send a request.**
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);
- Construct a command, which has parameter of the request.
(Omitted in above source) - Write command as AMF by ByteArray.writeObject()
- Create a URLRequest which has URL of GAE, and set data.
- Create a URLLoader, and send a request by load().
**Server(GAE): Decode command and exetute.**
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);
}
- Decode request as ICommand.
(※ICommand is the interface, which has only execute() method.) - Execute the execute() method of ICommand, and get the result.
- Store result data into Result instance and encode Result as AMF to return.
**Client(Flex): Get the request result**
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);
}
- Get the Result by ByteArray.readObject().
- Execute callback function.
#Following file contains above source files.
AMF48-GAESample