Electron+HTML做界面,C#做後臺(三)使用Socket組件StriveEngin實現通訊

Electron 和 C#控制檯程序通信

Electron+HTML做界面,C#做後臺(二) 中簡單說了線如何創建C#程序,並啓動Electron程序,那麼這節就說說兩者之間怎麼通信【C#使用StriveEngine.dll】或者百度相關信息

打開前面創建的項目

1.將debug目錄下的 electronApp複製一份到當前的項目目錄,

在這裏插入圖片描述

與vs創建的 bin目錄同級
在這裏插入圖片描述

2.在vs項目中 包含electronApp目錄文件(不要包含node_modules目錄,文件太多)

在這裏插入圖片描述

3.繼續選中文件,並選中右鍵屬性,複製到輸出目錄在這裏插入圖片描述

4. 添加類創建 Socket服務 ,類名稱 Services.cs【記得添加引用】

using StriveEngine;
using StriveEngine.Core;
using StriveEngine.Tcp.Server;
using System;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace ElectronHTMlCSharp
{
    /// <summary>
    /// 在本地開啓服務,監聽指定端口
    /// </summary>
    public class Services
    {
        public static Services services;

        private ITcpServerEngine SockterServerEngine;
        private bool IsSocketServerInitialized;
        public void StartServer()
        {
            try
            {
                if (SockterServerEngine == null)
                {
                    var port = AppTools.Get("port");
                    var _port = port == null || port.Length <= 0 ? 9909 : int.Parse(port);
                    SockterServerEngine = NetworkEngineFactory.CreateTextTcpServerEngine(_port, new DefaultTextContractHelper("\0"));//DefaultTextContractHelper是StriveEngine內置的ITextContractHelper實現。使用UTF-8對EndToken進行編碼。 
                }
                //判斷 相關的監聽事件是否註冊
                if (IsSocketServerInitialized)
                {
                    SockterServerEngine.ChangeListenerState(true);
                }
                else
                {
                    InitializeTcpServerEngine();
                }

                //this.ShowListenStatus();
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                if (ee.Message.IndexOf("there's one StriveEngine server instance running") >= 0)
                {
                    var res = MessageBox.Show("已打開一個實例或者前面實例的進程爲未完全退出,是否重啓?\r\n是:重啓\r\n否:關閉\r\n取消:不做任何處理", "警告", MessageBoxButtons.YesNoCancel);
                    if (DialogResult.Yes == res)
                    {
                        Application.ExitThread();
                        Application.Exit();
                        Application.Restart();
                        Process.GetCurrentProcess().Kill();
                    }
                    else if (DialogResult.No == res)
                    {
                        Application.ExitThread();
                        Application.Exit();
                        Process.GetCurrentProcess().Kill();
                    }
                }
            }
            services = this;
        }
        /// <summary>
        /// 爲 socket 註冊 服務事件
        /// </summary>
        private void InitializeTcpServerEngine()
        {
            //客戶端連接數量變化時,觸發事件
            SockterServerEngine.ClientCountChanged += new CbDelegate<int>(ClientCountChage);
            //客戶端與服務端建立連接時, 觸發事件
            SockterServerEngine.ClientConnected += new CbDelegate<IPEndPoint>(ClientConnected);
            //客戶端斷開連接時, 觸發事件
            SockterServerEngine.ClientDisconnected += new CbDelegate<IPEndPoint>(ClientDisconnected);
            //接受消息,觸發事件
            SockterServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(MessageReceived);

            //初始化tcp服務對象
            SockterServerEngine.Initialize();
            //標記tcp 服務已經初始化
            IsSocketServerInitialized = true;
        }

        /// <summary>
        ///  客戶端連接數量變化時,觸發事件
        /// </summary>
        private void ClientCountChage(int count)
        {
            Console.WriteLine("已連接數量" + count);
        }

        /// <summary>
        /// 客戶端與服務端建立連接時, 觸發事件
        /// </summary>
        /// <param name="IPEndPoint"></param>
        private void ClientConnected(IPEndPoint iPEndPoint)
        {
            var msg = string.Format("{0} 上線", iPEndPoint);
            Console.WriteLine(msg);
        }

        /// <summary>
        /// 斷開服務時, 觸發事件
        /// </summary>
        /// <param name="iPEndPoint"></param>
        private void ClientDisconnected(IPEndPoint iPEndPoint)
        {
            var msg = string.Format("{0} 下線", iPEndPoint);
            Console.WriteLine(msg);
        }

        /// <summary>
        /// 接受消息,觸發事件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="bMsg"></param>
        private void MessageReceived(IPEndPoint client, byte[] bMsg)
        {
            var msg = Encoding.UTF8.GetString(bMsg); //消息使用UTF-8編碼
            SendMsgToClient("接收到客戶端消息:" + msg, client);
        }

        /// <summary>
        /// 發送消息到指定的客戶端
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="client"></param>
        public void SendMsgToClient(string msg, IPEndPoint client)
        {
            var bMsg = System.Text.Encoding.UTF8.GetBytes(msg);//消息使用UTF-8編碼
            client = client ?? (IPEndPoint)SockterServerEngine.GetClientList()[0];
            SockterServerEngine.SendMessageToClient(client, bMsg);
        }
    }
}

4.2在Program.cs文件的Main方法中調用 Services ,添加如下代碼

    var ser = new Services();
    ser.StartServer();

最終如圖

在這裏插入圖片描述

5.創建 js文件用於前端socket請求工具類

5.1在 electronApp目錄下創建socket-helper.js

var top = top || {};

/**
 * 創建 sock實例併發送消息 ,短連接 ,發送一條消息之後就關閉
 * @param {any} ip 發送內容
 * @param {any} port 發送內容
 * @param {any} sendMsg 發送內容
 * @param {any} callGetMsg 得到消息的回調函數
 * @param {any} callOpen 連接之後服務端發送回 消息 執行的回調函數
 * @param {any} cllClose 關閉連接的回調函數,默認自動關閉
 */
function initSocket(ip, port, sendMsg,callGetMsg,callOpen,cllClose) {
    top.ip = top.ip || ip;
    top.port = top.port || port;
    var host = "ws://" + top.ip + ":" + top.port + "/"
    socket = new WebSocket(host);
    socket.onmessage = function (event) {
        if (typeof callGetMsg == "function")
            callGetMsg(event);
        if (typeof cllClose == "function") {
                cllClose(socket);
            } else {
            socket.close();
        }
    }
    socket.onopen = function (event) {
        if (typeof callOpen == "function")
            callOpen(event);
        socket.send(sendMsg);
    }
    return socket;
}

/**
 * 創建 sock實例併發送消息 ,短連接 ,發送一條消息之後就關閉
 * @param {any} sendMsg 發送內容
 * @param {any} callGetMsg 得到消息的回調函數
 * @param {any} callOpen 連接之後服務端發送回 消息 執行的回調函數
 * @param {any} cllClose 關閉連接的回調函數,默認自動關閉
 */
function initSockets(sendMsg, callGetMsg, callOpen, cllClose) {
    var host = "ws://" + top.ip + ":" + top.port + "/"
    socket = new WebSocket(host);
    socket.onmessage = function (event) {
        if (typeof callGetMsg == "function")
            callGetMsg(event);
        if (typeof cllClose == "function") {
            cllClose(socket);
        } else {
            socket.close();
        }
    }
    socket.onopen = function (event) {
        if (typeof callOpen == "function")
            callOpen(event);
        socket.send(sendMsg);
    }
    return socket;
}


/**
 * 創建 sock實例併發送消息 ,長連接
 * @param {any} sendMsg 發送內容
 * @param {any} callGetMsg 得到消息的回調函數
 * @param {any} callOpen 連接之後服務端發送回 消息 執行的回調函數
 * @param {any} cllClose 關閉連接的回調函數,默認自動關閉
 */
function initSocketLong(sendMsg, callGetMsg, callOpen, cllClose) {
    var host = "ws://" + top.ip + ":" + top.port + "/"
    socket = new WebSocket(host);
    socket.onmessage = function (event) {
        if (typeof callGetMsg == "function")
            callGetMsg(event);
        if (typeof cllClose == "function") {
            cllClose(socket);
        }
    }
    socket.onopen =  function (event) {
        if (typeof callOpen == "function")
            callOpen(event);
        sendMsg += (sendMsg.indexOf("?") > 0 ? "&" : "?") + "isLong=true";
        socket.send(sendMsg);
    }
    return socket;
}

5.2創建 socket頁面調用 js文件 hander.js

/***
 * 依賴文件 socket-helper.js
 * */

//配置 通信信息
function getSocketConf() {
    return {
        ip: '127.0.0.1',
        port: '9909'
    }
}

///**
// * 發送請求,返回後端處理的數據
// * @param {any} action action!method?par1=1&par2=2&parn=n&....
// * @param {any} callback 後端返回的回調函數
// */
//function Hander(action, callback) {
//    var con = getSocketConf();
//    top.ip = !top.ip ? con["ip"] : top.ip;
//    top.port = !top.port ? con["port"] : top.port;
//    initSockets(action, callback);
//}

/**
 * 發送請求,返回後端處理的數據
 * @param {any} action action!method?par1=1&par2=2&parn=n&....
 * @param {any} callback 後端返回的回調函數
 */
function Hander(action, callback) {
    var con = getSocketConf();
    top.ip = !top.ip ? con["ip"] : top.ip;
    top.port = !top.port ? con["port"] : top.port;
   return initSockets(action, callback, null, function (event) {});
}

/**
 * 發送請求,返回後端處理的數據 長鏈接 
 * @param {any} action action!method?par1=1&par2=2&parn=n&....
 * @param {any} callback 後端返回的回調函數
 */
function HanderLong(action, callback) {
    var con = getSocketConf();
    top.ip = !top.ip ? con["ip"] : top.ip;
    top.port = !top.port ? con["port"] : top.port;
    return initSocketLong(action, callback, null, function (event) { });
}

創建好的目錄如下

在這裏插入圖片描述

創建完兩個 js文件之後一定記得 右鍵屬性複製到輸出目錄

6之後我們需要在index.html頁面上使用socket進行通信,添加如下代碼

<!doctype html>
<html>
	<head>
		<title>hello Word</title>
	</head>
    <body>
        <h1>這是用Electron創建的程序,這個程序後面將會使用C#來實現數據邏輯處理</h1>
        <div>
            <input type="text" value="測試文字" id="text" />
            <input type="button" id="send" value="發送" />
            接受區域
            <div id="msg" style="width:100%;height:auto;border:1px solid #0094ff;">

            </div>
        </div>
        <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
        <script>if (typeof module === 'object') { top.$ = window.jQuery = window.$ = module.exports; };</script>
        <script src="socket-helper.js"></script>
        <script src="hander.js"></script>
        <script>
            $(function () {
                //偵聽 發送按鈕 事件,並將返C#端返回的數據 綁定到接受區域
                $("#send").on("click", function () {
                    var msg = $("#text").val();
                    Hander(msg, function (res) {
                        var html = $("#msg").html();
                        $("#msg").html(html + "<p>"+res.data+"</p>");
                    })
                });
            });
        </script>
    </body>
</html>

7.啓動vs項目

在這裏插入圖片描述
在這裏插入圖片描述

*** 如此前後臺就可以通行了,但是要注意 這個 websock框架對發送的字節大小有限制 ***

後面將會講述如何通過webSoket ,執行C# 指定類的指定的方法 【使用反射實現

如果你已經迫不及待,那麼請下載整個項目的源代碼,代碼已放置 GITHUB源碼下載,上面有最新的效果圖

如果覺得不錯,請打賞我,或者用錢侮辱我~_~!

在這裏插入圖片描述

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