【问题标题】:Receive ByteArray in Actionscript 3 from Java Servlet从 Java Servlet 接收 Actionscript 3 中的 ByteArray
【发布时间】:2012-07-07 00:01:35
【问题描述】:

我正在输入一个问题,但最后我解决了这个问题并且不想折腾它(并受到https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ 的鼓励),并决定分享我的问题解决方案。

问题是我想从 Java 应用程序服务器检索一些字节,这意味着,通过 Servlet 加载到 Flash 游戏中以获得重播功能。

有一些问题试图解决其他方式的问题,即从 as3 到服务器(php、java 等):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 URLRequestPushing ByteArray to POST。我没有找到与我分享的内容类似的内容(如果我错了,请纠正我)。

【问题讨论】:

  • 看来还要等7个小时才能回答!!!

标签: java actionscript-3 servlets request bytearray


【解决方案1】:

嗯,正如我在问题中所说,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,为游戏重播功能(用于调试目的)节省一些内存。

希望它有所帮助,并感谢任何批评者!

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多