跨平臺移動開發實戰(八)------移動客戶端網絡通信

服務器端搭建好後,移動客戶端就需要基於HTTP和Websocket來和服務器端通信,HTTP就基於Ajax來實現,Websocket就得靠各個移動平臺瀏覽器對Websocket的支持,基本的開發大家查查文檔就比較容易掌握,這裏我着重談三點:

  • Ajax安全策略
  • 移動平臺對Websocket的支持
  • 文件傳輸

1)Ajax安全策略

大家都知道Ajax存在跨域的限制,而基於Phonegap的離線開發實際上是本地HTML向server端發起Ajax請求,同樣會有安全限制,會導致你客戶端拿不到server端的返回信息,解決方法就是在servlet向客戶端寫數據之前加上如下代碼:

response.setHeader("Access-Control-Allow-Origin", "*");
2)移動平臺對Websocket的支持

網上有很多關於各大移動平臺的瀏覽器對Websocket的支持情況,而就我目前的實際測試來看,桌面Chrome、iphone/ipad上的safari、Webos和桌面firefox對Websocket支持都不錯,基本標準的API寫的程序都運行良好,但Android的chrome卻不支持Websocket,更麻煩的是phonegap也沒提供websocket的支持,因此在android需要寫phonegap plugin來支持websocket,不過有人做了這個事兒,https://github.com/anismiles/websocket-android-phonegap,需要做的是基於phonegap plugin的規範,加入這個插件即可。

3)文件傳輸

這裏說的文件傳輸不是基於瀏覽器默認的下載行爲,而是通過JS,由程序自行通過IO流把二進制文件從server端down到移動端的文件系統中。而這一點需要在不同的平臺上採取不同的方案:

  • 桌面chrome
    可以基於Webkit對IO和文件系統的支持來完成,具體細節可見如下samples:
    window.webkitRequestFileSystem(window.PERSISTENT, 30 * 1024 * 1024, function(fs){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', "http://"+host+":"+httpPort+"/syncFile?token="+token+"&id="+id, true);
        xhr.overrideMimeType('text/plain; charset=x-user-defined'); 
        xhr.responseType = "arraybuffer"; // Part of XHR 2
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                fs.root.getFile(fileName, {create: true},
                function(fileEntry) {
                    fileEntry.createWriter(function(writer) {  // FileWriter
                      writer.onwrite = function(e) { 
                          console.log("success download "+fileName);
                      };  // Success callback function
                      writer.onerror = function(e) {
                          console.log(e);
                      };  // Error callback function
                      var bb = new WebKitBlobBuilder();
                      bb.append(xhr.response);
                      writer.write(bb.getBlob("text/plain")); // The actual writing
                    }, errorHandler);
                  }); 
            }
        };
        xhr.send(); 
    },errorHandler);
    需要注意這和HTML5標準的file system API是有差異的,都帶有WebKit的前綴,這也許也是HTML5暫時沒法在各個平臺上得到統一的表現吧。
  • Android和IOS
    Android和IOS可以基於Phonegap提供的Filesystem和file transfer插件來完成,具體細節可見如下Samples(完成上例子同樣功能):
    window.requestFileSystem(
        LocalFileSystem.PERSISTENT, 0, function onFileSystemSuccess(fileSystem) {
            fileSystem.root.getDirectory(dirName, {create: true, exclusive: false}, function(dirEntry){
                var dirPath = dirEntry.fullPath;
                console.log(dirPath);
                var fileTransfer = new FileTransfer();
                var filePath = dirPath +"/"+ fileName;
                fileTransfer.download("http://"+host+":"+httpPort+"/syncFile?token="+token+"&id="+id, filePath,
                     function(theFile) {
                        console.log("download complete: " + theFile.toURI());
                     },
                     function(error) {
                         console.log("download error source " + error.source);
                         console.log("download error target " + error.target);
                         console.log("upload error code: " + error.code);
                     }
                 );
            }, fail);
           }, 
    fail);
  • Webos
    Webos需要通過mojo提供的service來完成:
    navigator.service.Request('palm://com.palm.downloadmanager/', {
        method: 'download',
        parameters: {
            target: url,
            targetDir : "/media/internal/files/"+dirName,
            targetFilename : fileName,
            keepFilenameOnRedirect: false,
            subscribe: true
        },
        onSuccess : function (e){ console.log("Download success, results="+JSON.stringify(e)); },
        onFailure : function (e){ console.log("Download failure, results="+JSON.stringify(e)); }
    });

有關文件系統訪問的細節我會單獨拿出來分析。

另外,由於Websocket目前對二進制的數據傳輸的支持不夠好,所以當需要server端向客戶端推送二進制文件時,我的方案是server端通過websocket向客戶端發一個文件下載的通知,客戶端收到通知後再通過上述的相應方案來下載文件:

websocket.onmessage = function(e) {
    console.log(e.data);
    var token = getToken();
    var r=eval("("+e.data+")"); 
    if(r.type == 'syncList'){
        for(var i=0;i<r.data.length;i++){
            device.syncFile(token, r.data[i].id, r.data[i].name);
        }
    }
}
r.data[i].id和r.data[i].name是需要下載文件的標識,通過這個標識能對應到文件下載的URL,雖然這個方案不完美,但還比較健壯。不過,通過Websocket直接傳輸文件雖然想起來複雜,但肯定是走得通的,等這塊實驗成功後我再補充到這裏。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章