Reputation: 61
I was typing a question but finally I solved the problem and don't wanted to toss it (and encouraged by https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/), and decided to share my problem-solution.
The problem is that I want to retrieve some bytes from a Java application server, that means, via a Servlet to load in a flash game for a replay feature.
There are some questions trying to solve the other way problem, that means, from as3 to a server (php, java, etc): How to send binary data from AS3 through Java to a filesystem?, How can I send a ByteArray (from Flash) and some form data to php?, Uploading bytearray via URLRequest and Pushing ByteArray to POST. I didn't find something like what I'm sharing (correct me if I'm wrong).
Upvotes: 0
Views: 1314
Reputation: 61
Well, as I said in the question, I was encouraged by StackOverflow to answer and here it is:
The Servlet doGet method that gives the byte array:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
MouseInput oneInput = getMouseInput(); //abstracted (I'm using google appengine)
byte[] inputInBytes = oneInput.getInBytes();
OutputStream o = resp.getOutputStream();
o.write(inputInBytes);
o.flush();
o.close();
}
MouseInput.getInBytes method body:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(this.type);
dos.writeDouble(this.localX);
dos.writeDouble(this.localY);
dos.writeBoolean(this.buttonDown);
return baos.toByteArray();
My Actionscript code to receive the byte array data:
var url:String = "http://localhost:8888/input"; //servlet url
var request:URLRequest = new URLRequest(url);
//get rid of the cache issue:
var urlVariables:URLVariables = new URLVariables();
urlVariables.nocache = new Date().getTime();
request.data = urlVariables;
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, function (evt:Event) {
var loader:URLLoader = URLLoader(evt.target);
var bytes:ByteArray = loader.data as ByteArray;
trace(bytes); //yeah, you'll get nothing!
//the bytes obtained from the request (see Servlet and
//MouseInput.getInBytes method body code above) were written in
//the sequence like is read here:
trace(bytes.readInt());
trace(bytes.readDouble());
trace(bytes.readDouble());
trace(bytes.readBoolean());
}
loader.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event) {
trace("error");
});
loader.load(request);
Well, it works! Obviously you can make some adjustments, like not using the anonymous function for better reading, but to illustrate it was ok! Now I can save some memory to a game replay feature (for debug purpose) with ByteArray instead of heavy XML that I was trying.
Hope it helped and any critics is appreciated!
Cheers
Upvotes: 2