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

Electron 和 C#控制臺程序通信

Electron+HTML做界面,C#做后臺(二) 中簡單說了線如何創(chuàng)建C#程序,并啟動Electron程序,那么這節(jié)就說說兩者之間怎么通信【C#使用StriveEngine.dll】或者百度相關(guān)信息

打開前面創(chuàng)建的項目

1.將debug目錄下的 electronApp復(fù)制一份到當(dāng)前的項目目錄,

在這里插入圖片描述

與vs創(chuàng)建的 bin目錄同級

在這里插入圖片描述

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

在這里插入圖片描述

3.繼續(xù)選中文件,并選中右鍵屬性,復(fù)制到輸出目錄
在這里插入圖片描述

4. 添加類創(chuàng)建 Socket服務(wù) ,類名稱 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>
    /// 在本地開啟服務(wù),監(jiān)聽指定端口
    /// </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內(nèi)置的ITextContractHelper實現(xiàn)。使用UTF-8對EndToken進行編碼。 
                }
                //判斷 相關(guān)的監(jiān)聽事件是否注冊
                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否:關(guā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 注冊 服務(wù)事件
        /// </summary>
        private void InitializeTcpServerEngine()
        {
            //客戶端連接數(shù)量變化時,觸發(fā)事件
            SockterServerEngine.ClientCountChanged += new CbDelegate<int>(ClientCountChage);
            //客戶端與服務(wù)端建立連接時, 觸發(fā)事件
            SockterServerEngine.ClientConnected += new CbDelegate<IPEndPoint>(ClientConnected);
            //客戶端斷開連接時, 觸發(fā)事件
            SockterServerEngine.ClientDisconnected += new CbDelegate<IPEndPoint>(ClientDisconnected);
            //接受消息,觸發(fā)事件
            SockterServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(MessageReceived);

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

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

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

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

        /// <summary>
        /// 接受消息,觸發(fā)事件
        /// </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>
        /// 發(fā)送消息到指定的客戶端
        /// </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方法中調(diào)用 Services ,添加如下代碼

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

最終如圖

在這里插入圖片描述

5.創(chuàng)建 js文件用于前端socket請求工具類

5.1在 electronApp目錄下創(chuàng)建socket-helper.js

var top = top || {};

/**
 * 創(chuàng)建 sock實例并發(fā)送消息 ,短連接 ,發(fā)送一條消息之后就關(guān)閉
 * @param {any} ip 發(fā)送內(nèi)容
 * @param {any} port 發(fā)送內(nèi)容
 * @param {any} sendMsg 發(fā)送內(nèi)容
 * @param {any} callGetMsg 得到消息的回調(diào)函數(shù)
 * @param {any} callOpen 連接之后服務(wù)端發(fā)送回 消息 執(zhí)行的回調(diào)函數(shù)
 * @param {any} cllClose 關(guān)閉連接的回調(diào)函數(shù),默認自動關(guān)閉
 */
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;
}

/**
 * 創(chuàng)建 sock實例并發(fā)送消息 ,短連接 ,發(fā)送一條消息之后就關(guān)閉
 * @param {any} sendMsg 發(fā)送內(nèi)容
 * @param {any} callGetMsg 得到消息的回調(diào)函數(shù)
 * @param {any} callOpen 連接之后服務(wù)端發(fā)送回 消息 執(zhí)行的回調(diào)函數(shù)
 * @param {any} cllClose 關(guān)閉連接的回調(diào)函數(shù),默認自動關(guān)閉
 */
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;
}


/**
 * 創(chuàng)建 sock實例并發(fā)送消息 ,長連接
 * @param {any} sendMsg 發(fā)送內(nèi)容
 * @param {any} callGetMsg 得到消息的回調(diào)函數(shù)
 * @param {any} callOpen 連接之后服務(wù)端發(fā)送回 消息 執(zhí)行的回調(diào)函數(shù)
 * @param {any} cllClose 關(guān)閉連接的回調(diào)函數(shù),默認自動關(guān)閉
 */
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創(chuàng)建 socket頁面調(diào)用 js文件 hander.js

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

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

///**
// * 發(fā)送請求,返回后端處理的數(shù)據(jù)
// * @param {any} action action!method?par1=1&par2=2&parn=n&....
// * @param {any} callback 后端返回的回調(diào)函數(shù)
// */
//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);
//}

/**
 * 發(fā)送請求,返回后端處理的數(shù)據(jù)
 * @param {any} action action!method?par1=1&par2=2&parn=n&....
 * @param {any} callback 后端返回的回調(diào)函數(shù)
 */
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) {});
}

/**
 * 發(fā)送請求,返回后端處理的數(shù)據(jù) 長鏈接 
 * @param {any} action action!method?par1=1&par2=2&parn=n&....
 * @param {any} callback 后端返回的回調(diào)函數(shù)
 */
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) { });
}

創(chuàng)建好的目錄如下

在這里插入圖片描述

創(chuàng)建完兩個 js文件之后一定記得 右鍵屬性,復(fù)制到輸出目錄

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

<!doctype html>
<html>
    <head>
        <title>hello Word</title>
    </head>
    <body>
        <h1>這是用Electron創(chuàng)建的程序,這個程序后面將會使用C#來實現(xiàn)數(shù)據(jù)邏輯處理</h1>
        <div>
            <input type="text" value="測試文字" id="text" />
            <input type="button" id="send" value="發(fā)送" />
            接受區(qū)域
            <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 () {
                //偵聽 發(fā)送按鈕 事件,并將返C#端返回的數(shù)據(jù) 綁定到接受區(qū)域
                $("#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框架對發(fā)送的字節(jié)大小有限制 ***

后面將會講述如何通過webSoket ,執(zhí)行C# 指定類的指定的方法 【使用反射實現(xiàn)

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容