js如何操作本地程序

背景

假設有這樣一個產品,一個web和一個winform客戶端,在客戶在web的網頁上面點擊啓動客戶端來處理,這個時候開始調用本地的客戶端,來完成指定的工作。這種場景在日常的上網中也比較常見,如使用迅雷下載。當然實現的方式也有很多種,今天我來演示一種用監控Http請求來實現這個功能,思路如下:

HttpListener

對於上面的分析,最重要的功能雖實現對Http的監控,而.net中已經封裝了我們的需求,下面看下如何具體的實現:

   static void Main(string[] args)
    {
        HttpListener listerner = new HttpListener();

        try
        {
            listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份驗證 Anonymous匿名訪問
            listerner.Prefixes.Add("http://localhost:8080/Service/");
            listerner.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine("無法啓動監視:" + ex.Message);
        }

        Task.Factory.StartNew(() =>  //使用一個線程對監聽
        {
            while (true)
            {
                HttpListenerContext ctx = listerner.GetContext();
                Task.Factory.StartNew(TaskProc, ctx);//回調函數,開啓新線程進行調用,不影響下次監聽
            }
        });

        Console.ReadKey();
    }

實現請求的響應

現在我們可以拿到請求的上下文的信息ctx,先定義一個參數的格式,簡單的定義如下:

    public class ReciveInfo
    {
        public string path { get; set; }//應用程序所在的路徑

        public string name { get; set; }//應用程序名稱
    }

下面對ctx的Response數據進行填寫.

    static void TaskProc(object o)
    {
        HttpListenerContext ctx = (HttpListenerContext)o;
        StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8);
        try
        {
            //接收POST參數
            Stream stream = ctx.Request.InputStream;
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            String body = HttpUtility.UrlDecode(reader.ReadToEnd());
            Console.WriteLine(body);
            var reciveInfo = Json.JsonParser.Deserialize<ReciveInfo>(body);
            Process.Start(reciveInfo.path);
             ctx.Response.Headers.Add("Access-Control-Allow-Origin","*"); //防止出現跨域的問題錯誤
            ctx.Response.StatusCode = 200; //設置返回給客服端http狀態代碼
            writer.Write(reciveInfo.name + "啓動成功");
        }

        catch (ArgumentException e)
        {
            ctx.Response.StatusCode = 500;
            writer.Write("參數有誤:" + e.Message);
        }
        catch (Exception e)
        {
            ctx.Response.StatusCode = 500;
            writer.Write("程序異常:" + e.Message);
        }
        finally
        {
            writer.Close();
            ctx.Response.Close();
        }

    }

測試

在測試中我在js中啓動我電腦中的QQ,具體的代碼如下:

	<button id="btnQQ"> start QQ</button>
	<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
	<script type="text/javascript">
	$(function() {
	    $("#btnQQ").click(function() {

	        $.ajax({
	            type: "POST",
	            url: "http://localhost:8080/Service",
	            dataType: "json",
	            data: JSON.stringify({
	                path: "D:/Program Files/Tencent/QQ/Bin/QQScLauncher.exe",
	                name: "qq"
	            }) 
	        });
	    });
	});
	</script>

啓動後,運行截圖如下:

(本文完)

作者:老付 如果覺得對您有幫助,可以下方的訂閱,或者選擇右側捐贈作者,如果有問題,請在捐贈後諮詢,謝謝合作 如有任何知識產權、版權問題或理論錯誤,還請指正。 自由轉載-非商用-非衍生-保持署名,請遵循:創意共享3.0許可證 交流請加羣113249828:點擊加羣 或發我郵件 [email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章