簡體   English   中英

從Java Servlet接收Actionscript 3中的ByteArray

[英]Receive ByteArray in Actionscript 3 from Java Servlet

我正在輸入一個問題,但最后我解決了這個問題並且不想拋棄它(並且受到http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your的鼓勵-own-questions / ),並決定分享我的問題解決方案。

問題是我想從Java應用程序服務器中檢索一些字節,這意味着,通過Servlet加載到Flash游戲中以獲得重放功能。

有一些問題試圖解決另一種問題,即從as3到服務器(php,java等): 如何通過Java將二進制數據從AS3發送到文件系統? 我怎樣才能將ByteArray(來自Flash)和一些表單數據發送到php? 通過URLRequest上傳bytearray並將ByteArray推送到POST 我找不到像我分享的東西(如果我錯了,請糾正我)。

好吧,正如我在問題中所說,StackOverflow鼓勵我回答,這里是:

給出字節數組的Servlet doGet方法:

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方法體:

   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();

我的Actionscript代碼接收字節數組數據:

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);

好吧,它的作品! 顯然你可以做一些調整,比如不使用匿名函數來更好地閱讀,但為了說明它沒關系! 現在,我可以使用ByteArray將一些內存保存到游戲重放功能(用於調試目的),而不是我正在嘗試的重型XML。

希望它有所幫助,任何評論家都表示贊賞!

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM