在Visual Studio 2019上使用C# 創建用於webstock的windows服務 實現一鍵打包安裝自啓動

本人是主要是做PHP開發, 在做Windows的WebStock服務的過程中 借鑑了很多文章 踩了無數的坑 最終完成 代碼部分大多是從網上Copy而來 但是具體是從哪篇文章找到的 具體已經記得不太清楚了 不過在此感謝各位大大的分享…

以下 將一步步介紹使用C# 在VS2019平臺 從開始創建服務 到寫入WebStock 直到最後打包完成 並生成安裝文件 並設置自啓動的詳細步驟
1:創建C# windows服務(基於.NET Framework) PS:第一個坑 我第一次選擇了(基於.NET Core)
在這裏插入圖片描述
2:設置項目名稱 選擇項目位置 與相關框架
在這裏插入圖片描述
3:設置服務名稱 服務屬性 開機啓動
右鍵->添加安裝程序->選擇serviceInstaller1->右下鍵 設置ServiceName服務名稱、DisplayName服務通用名、Description服務描述、StartType服務啓動類型-Automatic(自動),可用類型分別爲Automatic(自動)、Manual(手動)、Disabled(禁用)。
<<此步驟不確定是否必須>>
繼續選擇->選擇左上serviceProcessInstaller1->設置Account賬戶類型爲LocalSystem(系統服務)
在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述
4:創建WebStock代碼 基本都是網上在各位博客下一點點拼湊出來的 沒有封裝。
先貼部分圖片代碼 最後貼上全部代碼
在這裏插入圖片描述在這裏插入圖片描述
5:代碼完成後,因爲是服務程序,可能會無法執行。 可以使用命令 installutil嘗試 或者繼續下面的打包流程。 打包流程:在解決方案處右鍵->添加->新建項目->選擇Setup Project.
PS:2019安裝包內不再提供打包項,需手動安裝
下載地址:https://visualstudioclient.gallerycdn.vsassets.io/extensions/visualstudioclient/microsoftvisualstudio2017installerprojects/0.9.6/1581535947082/InstallerProjects.vsix
下載完成後雙擊安裝後再創建項目處可見.
在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述
6:打包程序設置 這一步比較多的操作 但其實也沒有多繁瑣
1)左側->Application Folder右鍵->Add->項目輸出->選擇項目->確定.
2)右側項目列表->選擇當前的安裝項目 右鍵->View->自定義操作
3)左側->Install,Commit,Rollback,Uninstall 4項依次點擊右鍵->添加自定義操作->雙擊彈窗出的 Application Folder->選擇主輸出->確定.
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
7:自啓動
此時 生成項目 就可以生成安裝包進行安裝服務了。但當前服務不能自啓動。還需要在服務項目中變形安裝完成後的代碼.
選擇我們的項目->右鍵生成出的項目安裝cs文件->查看代碼->寫入如下代碼.
在這裏插入圖片描述
8:生成安裝文件 安裝
右側菜單->安裝項目->右鍵->生成.
在項目目錄中可以找到當前項目安裝的iso文件與exe文件.
安裝完成後 服務自動運行.
在這裏插入圖片描述
9:創建一個HTML 簡易的Js代碼嘗試連接WebStock。

在這裏插入圖片描述
10:至此全部完成.以下是程序代碼.
C#服務代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace MyWebStockService
{
    public partial class Service1 : ServiceBase
    {
        static List<Socket> Sockets = new List<Socket>();
        static Thread t;
        static Thread th;
        public Service1()
        {
            InitializeComponent();
        }
        //服務開啓執行代碼
        protected override void OnStart(string[] args)
        {
            
            // 自定義一個端口
            int port = 61212; 
            // 創建一個WebStock服務
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
            Socket listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            //由於服務需要快速啓動完成 不然有可能會超時無響應 所以選擇創建線程來執行
            th = new Thread(new ThreadStart(() => CreateAccept(listener, localEP)));
            th.IsBackground = true;
            th.Start();
        }
        //關閉服務執行代碼
        protected override void OnStop()
        {
            //關閉相關線程
            if (t != null && t.ThreadState == System.Threading.ThreadState.Running)
                t.Abort();
            if (th != null && th.ThreadState == System.Threading.ThreadState.Running)
                th.Abort();
        }

        /// <summary>
        /// 接受WebStock的連接
        /// </summary>
        /// <param name="listener">Stock</param>
        /// <param name="localEP">連接信息</param>
        /// <returns></returns>
        public static void CreateAccept(Socket listener, IPEndPoint localEP)
        {
            listener.Bind(localEP);
            listener.Listen(10);
            while (true)
            {
                //接受一個連接
                Socket sc = listener.Accept();

                //添加到緩存
                Sockets.Add(sc);

                //創建Socket多線程,以保證多用戶連接, 去執行獲取數據的動作,與客戶端通信 
                t = new Thread(new ThreadStart(() => ReceiveData(sc)));
                t.IsBackground = true;
                t.Start();
            }
        }
        /// <summary>
        /// Stock的數據交互
        /// </summary>
        /// <param name="sc">當前的連接</param>
        /// <returns></returns>
        public static void ReceiveData(Socket sc)
        {
            byte[] buffer = new byte[1024];
            //握手
            int length = sc.Receive(buffer);//接受客戶端握手信息
            sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length))); while (true)
            {
                //接受客戶端數據
                length = sc.Receive(buffer);
                string clientMsg = AnalyticData(buffer, length);
                //發送數據
                string sendMsg = "服務端返回信息:" + clientMsg;
                sc.Send(PackData(sendMsg));
            }
        }
        /// <summary>
        /// 打包握手信息
        /// </summary>
        /// <param name="secKeyAccept">Sec-WebSocket-Accept</param>
        /// <returns>數據包</returns>
        private static byte[] PackHandShakeData(string secKeyAccept)
        {
            var responseBuilder = new StringBuilder();
            responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
            responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
            responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
            responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);
            //如果把上一行換成下面兩行,纔是thewebsocketprotocol-17協議,但居然握手不成功,目前仍沒弄明白!
            //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);
            //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);

            return Encoding.UTF8.GetBytes(responseBuilder.ToString());
        }

        /// <summary>
        /// 生成Sec-WebSocket-Accept
        /// </summary>
        /// <param name="handShakeText">客戶端握手信息</param>
        /// <returns>Sec-WebSocket-Accept</returns>
        private static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength)
        {
            string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
            string key = string.Empty;
            Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
            Match m = r.Match(handShakeText);
            if (m.Groups.Count != 0)
            {
                key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
            }
            byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
            return Convert.ToBase64String(encryptionString);
        }

        /// <summary>
        /// 解析客戶端數據包
        /// </summary>
        /// <param name="recBytes">服務器接收的數據包</param>
        /// <param name="recByteLength">有效數據長度</param>
        /// <returns></returns>
        private static string AnalyticData(byte[] recBytes, int recByteLength)
        {
            if (recByteLength < 2) { return string.Empty; }

            bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最後一幀  
            if (!fin)
            {
                return string.Empty;// 超過一幀暫不處理 
            }

            bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩碼  
            if (!mask_flag)
            {
                return string.Empty;// 不包含掩碼的暫不處理
            }

            int payload_len = recBytes[1] & 0x7F; // 數據長度  

            byte[] masks = new byte[4];
            byte[] payload_data;

            if (payload_len == 126)
            {
                Array.Copy(recBytes, 4, masks, 0, 4);
                payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 8, payload_data, 0, payload_len);

            }
            else if (payload_len == 127)
            {
                Array.Copy(recBytes, 10, masks, 0, 4);
                byte[] uInt64Bytes = new byte[8];
                for (int i = 0; i < 8; i++)
                {
                    uInt64Bytes[i] = recBytes[9 - i];
                }
                UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);

                payload_data = new byte[len];
                for (UInt64 i = 0; i < len; i++)
                {
                    payload_data[i] = recBytes[i + 14];
                }
            }
            else
            {
                Array.Copy(recBytes, 2, masks, 0, 4);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 6, payload_data, 0, payload_len);

            }

            for (var i = 0; i < payload_len; i++)
            {
                payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);
            }

            return Encoding.UTF8.GetString(payload_data);
        }


        /// <summary>
        /// 打包服務器數據
        /// </summary>
        /// <param name="message">數據</param>
        /// <returns>數據包</returns>
        private static byte[] PackData(string message)
        {
            byte[] contentBytes = null;
            byte[] temp = Encoding.UTF8.GetBytes(message);

            if (temp.Length < 126)
            {
                contentBytes = new byte[temp.Length + 2];
                contentBytes[0] = 0x81;
                contentBytes[1] = (byte)temp.Length;
                Array.Copy(temp, 0, contentBytes, 2, temp.Length);
            }
            else if (temp.Length < 0xFFFF)
            {
            	//開始使用這種方法時候超過126字節傳輸失敗 使用第二種後可以 後第一種也可以了
                /*
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length & 0xFF);
                contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
                */
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length & 0xFF);
                contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
            }
            else
            {
                //未測試是否可行  
                contentBytes = new byte[temp.Length + 10];
                contentBytes[0] = 0x81;
                contentBytes[1] = 127;
                contentBytes[2] = 0;
                contentBytes[3] = 0;
                contentBytes[4] = 0;
                contentBytes[5] = 0;
                contentBytes[6] = (byte)(temp.Length >> 24);
                contentBytes[7] = (byte)(temp.Length >> 16);
                contentBytes[8] = (byte)(temp.Length >> 8);
                contentBytes[9] = (byte)(temp.Length & 0xFF);
                Array.Copy(temp, 0, contentBytes, 10, temp.Length); 
            }

            return contentBytes;
        }
    }
}

C#自啓動代碼:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;

namespace MyWebStockService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
        //項目安裝完成後執行
        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
            //聲明服務 變量爲: 通用名 
            ServiceController sc = new ServiceController("我的WebStock服務");
            if (sc.Status.Equals(ServiceControllerStatus.Stopped))
            {
                sc.Start();
            }
        }
    }
}

HTML JS代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
    <script type="text/javascript">
        var ws;
        function ToggleConnectionClicked() {
            try {
                var SOCKECT_ADDR = "ws://127.0.0.1:61212/chat";
                ws = new WebSocket(SOCKECT_ADDR);	
                ws.onopen = function (event) { 
					alert("已經與服務器建立了連接\r\n當前連接狀態:" + this.readyState); 
                	ws.send("success");
				};
                ws.onmessage = function (event) { alert("接收到服務器發送的數據:\r\n" + event.data); };
                ws.onclose = function (event) { alert("已經與服務器斷開連接\r\n當前連接狀態:" + this.readyState); };
                ws.onerror = function (event) {
					alert("WebSocket異常!" + event.toString());
				};
            } catch (ex) {
                alert(ex.message);
            }
        };
 
        function SendData() {
            try {
                ws.send("success");
            } catch (ex) {
                alert(ex.message);
            }
        };
 
        function seestate() {
            alert(ws.readyState);
        }
       
    </script>
</head>
<body>
    <button id='ToggleConnection1' type="button" onClick='ToggleConnectionClicked();'>
        連接服務器</button><br />
    <br />
    <button id='ToggleConnection2' type="button" onClick='SendData();'>
        發送我的名字:beston</button><br />
    <br />
    <button id='ToggleConnection3' type="button" onClick='seestate();'>
        查看狀態</button><br />
    <br />
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章