1. 程式人生 > >手機app內建http伺服器實現電腦端訪問手機html頁面(上)

手機app內建http伺服器實現電腦端訪問手機html頁面(上)

一、準備及原型

  1. 前言 這個暑假接了一個小專案,用cordova實現一個表型採集的app,其中一個檔案傳輸匯入匯出的的需求使:手機端開啟服務,在同一個wifi環境下,電腦瀏覽器進行訪問手機ip地址,然後顯示出手機暴露的頁面,再進行相關的操作。
    第一念頭:什麼鬼的需求!
    這裡寫圖片描述
    但是還是硬著頭皮按照產品經理學長的的意思,畫出該功能相關的原型:
  2. 原型
    手機端:
    這裡寫圖片描述
    電腦端:
    這裡寫圖片描述

二、httpd外掛

1..思路分析
大概就是上述原型的意思了,這個有點像小米檔案管理中的遠端管理功能,不過它的是ftp協議的服務,只能進行簡單的檔案傳輸。而需求是可以訪問到html頁面。
按照這種思路即是將手機變成一個http伺服器,這樣需要重寫很多東西,這個專案是基於html的移動app,採用的是cordova 框架,於是我先去cordova 官方外掛,功夫不負有心人,找到了一個httpd的外掛。

cordova plugin add cordova-plugin-httpd

新增成功
2. api:先是看了一下readme提供的api,嗯只有四個分別是啟動服務、停止服務,顯示手機暴露的ip、顯示根目錄

startServer( options, success_callback, error_callback );

stopServer( success_callback, error_callback );

getURL( success_callback, error_callback );

getLocalPath( success_callback, error_callback )
;

三 、使用及開發

1 . index.html介面分別建立四個按鈕

    <p><button onclick="startServer('');">Start CorHttpd at assets/www/filetransfer</button></p>
    <p><button onclick="startServer('/');">Start CorHttpd at /</button></p>
    <p><button onclick="stopServer();"
>
Stop CorHttpd</button></p> <p><button onclick="updateStatus();">Check Status</button></p>

2 .根據外掛的示例編寫js

 var httpd = null;
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }
    function onDeviceReady() {
        httpd = ( cordova && cordova.plugins && cordova.plugins.CorHttpd ) ? cordova.plugins.CorHttpd : null;

        startServer("");
    }
    function updateStatus() {
        document.getElementById('location').innerHTML = "document.location.href: " + document.location.href;
        if( httpd ) {
            httpd.getURL(function(url){
                if(url.length > 0) {
                    document.getElementById('url').innerHTML = "server is up: <a href='" + url + "' target='_blank'>" + url + "</a>";
                } else {
                    document.getElementById('url').innerHTML = "server is down.";
                }
            });
            httpd.getLocalPath(function(path){
                document.getElementById('localpath').innerHTML = "<br/>localPath: " + path;
            });
        } else {
            alert('CorHttpd plugin not available/ready.');
        }
    }
    function startServer( wwwroot ) {
        if ( httpd ) {
            httpd.getURL(function(url){
                if(url.length > 0) {
                    document.getElementById('url').innerHTML = "server is up: <a href='" + url + "' target='_blank'>" + url + "</a>";
                } else {
                    httpd.startServer({
                        'www_root' : wwwroot,
                        'port' : 8080
                    }, function( url ){
                        document.getElementById('url').innerHTML = "server is started: <a href='" + url + "' target='_blank'>" + url + "</a>";
                    }, function( error ){
                        document.getElementById('url').innerHTML = 'failed to start server: ' + error;
                    });
                }

            },function(){});
        } else {
            alert('CorHttpd plugin not available/ready.');
        }
    }
    function stopServer() {
        if ( httpd ) {
            httpd.stopServer(function(){
                document.getElementById('url').innerHTML = 'server is stopped.';
            },function( error ){
                document.getElementById('url').innerHTML = 'failed to stop server' + error;
            });
        } else {
            alert('CorHttpd plugin not available/ready.');
        }
    }


    function createFile() {
        var type = window.TEMPORARY;
        var size = 5*1024*1024;

        window.requestFileSystem(type, size, successCallback, errorCallback)

        function successCallback(fs) {
            fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
                alert('File creation successfull!')
            }, errorCallback);
        }

        function errorCallback(error) {
            alert("ERROR: " + error.code)
        }

    }

3 . 執行
安裝app,手機端並啟動服務,當電腦端和手機在同一網路環境下,電腦端訪問地址。
手機端:
這裡寫圖片描述
電腦端
這裡寫圖片描述
是我們手機端的index.html,也就是說暴露的就是我們編輯的頁面,之前的需求端要求的頁面是自定義的,所以應該可以自定義一個頁面讓手機端進行暴露。

4 . 修改原始碼指定要暴露的頁面
這裡寫圖片描述
找到外掛的java原始碼 在選中的java 檔案中查詢index.html,改為自己制訂暴露的html頁面

    if ( res == null )
            {
                // First try index.html and index.htm 
                if ( new AndroidFile( f, "filetransfer.html" ).exists())
                    f = new AndroidFile( homeDir, uri + "/filetransfer.html" );
                else if ( new AndroidFile( f, "filetransfer.htm" ).exists())
                    f = new AndroidFile( homeDir, uri + "/filetransfer.htm" );
                // No index file, list the directory if it is readable
                else if ( allowDirectoryListing && f.canRead() )

5.結果
電腦端顯示介面,成功實現
這裡寫圖片描述
下一步就是檔案的相關操作了。