您的位置:首页 > 理论基础 > 计算机网络

XMLHttp java服务端与 js客户端通讯实现二进制流收发

2016-06-03 10:54 253 查看
XMLHttp  java服务端与 js客户端通讯实现二进制流收发

js客户端:

var xhr = cc.loader.getXMLHttpRequest();
xhr.responseType = "arraybuffer";
var that = this;

xhr.onreadystatechange = function () {

if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {

var binary = new Uint8Array(xhr.response);
 }
}

xhr.open("POST", "http://192.168.199.88:8787");

var str = "test=1&idLogin=10086";
var buf = new ArrayBuffer(str.length); // 1 bytes for each char
var view = new Uint8Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
view[i] = str.charCodeAt(i);
}

xhr.send(buf);

参考如下:http://blog.csdn.net/u011462674/article/details/9748359

利用XMLHttpRequest同步和异步下载二进制文件的解决方案。

在XMLHttpRequest里支持二进制数据的下载了,现分别以同步和异步两种方式分别介绍。

异步的方式下载:

[html]
view plain
copy

  

[javascript]
view plain
copy

xmlRequest.open("GET", "0.jpg", true);  
xmlRequest.responseType = "blob";//这里是关键,它指明返回的数据的类型是二进制  
xmlRequest.onreadystatechange = function(e) {  
    if (this.readyState == 4 && this.status == 200) {  
        var response = this.response;  
        img.src = window.URL.createObjectURL(response);  
    }  
}  
xmlRequest.send(null);  

同步的方式下载:

[html]
view plain
copy

<pre name="code" class="javascript">    xmlRequest.open("GET", "0.jpg", false);  
    xmlRequest.overrideMimeType('text/plain; charset=x-user-defined');//这里是关键,不然 this.responseText;的长度不等于文件的长度  
    xmlRequest.onreadystatechange = function(e) {  
    if (this.readyState == 4 && this.status == 200) {  
              var text = this.responseText;  
              var length = text.length;  
              var array = new Uint8Array(length);  
              for (var i = 0; i < length; ++i) {  
                  array[i] = text.charCodeAt(i);  
              }  
              var blob = new Blob([array], { "type": "image/jpeg" });  
              img.src = window.URL.createObjectURL(blob);  
          }  
      }  
    xmlRequest.send(null);</pre><br>  
<pre></pre>  
注意:w3c标准中规定同步的情况下是不能设置responseType属性的。  
<p></p>  
<p></p>  
<p></p>  
<pre></pre>  
<pre></pre>  
<pre></pre>  
    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: