SignalR-WinForm服務端


  最近有項目需求,要實現在網頁上獲取服務器信息。大家都知道,網頁程序很難獲取客戶端信息比如MAC、CPU、硬盤信息等等。當時想過一些種方案,比如:通過IE插件,但只能用IE瀏覽器。正為這事焦頭爛額時,一天回家的路上,突發靈感,能不能在客戶端放一個服務,通過 訪問這個服務,這樣就可以解決。但問題又來了, 能訪問什么樣的服務Socker、WebSocker、SOCKET.IO,SignalR。經過一調研,親自創建事例程序實踐,個人感覺最好用的方式是:SignalR。

  使用Socker、WebSocker也功能上也可以實現,只是開發是量過大並且難以控制。

  相關文章的地址:

  WebSocker:http://www.cnblogs.com/dolphinX/p/3462898.html

  SOCKET.IO:https://socket.io/

  • 服務器端(WinForm)
  1. 創建WinForm程序 SignalRService
  2. 添加新項-OWIN Startup類

     

  3. 添加GIT包引用

  4.  安裝兩個NuGet包

    Microsoft.Owin.SelfHost
    Microsoft.AspNet.SignalR.SelfHost

     

  5. 創建MoveTextHub類,需要繼承於: Hub。在類上面添加[HubName("getMessage")]Hub的別名,方便前台調用
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    //Hub的別名,方便前台調用
    //[HubName("getMessage")]
    public class MyHub : Hub
    {
        /// <summary>
        /// 編寫發送信息的方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="message"></param>
        public void Send(string name, string message)
        {
            //調用所有客戶注冊的本地的JS方法(addMessage)
            Clients.All.addMessage(name, message);
        }
    } 
  6. 設置剛剛創建的Startup1
    using Microsoft.Owin.Cors;
    using Owin;
    
    namespace SignalRService
    {
        public class Startup1
        {
            public void Configuration(IAppBuilder app)
            {
                // 有關如何配置應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkID=316888
                app.UseCors(CorsOptions.AllowAll);
                app.MapSignalR();
            }
        }
    }

     


     

  7. 主窗體,兩個按鈕,一個啟動,一個停止,還有一個文本框,用於顯示輸出信息。
    代碼如下
    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Microsoft.Owin.Hosting;
    
    namespace SignalRService
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            public IDisposable SignalR { get; set; }
            private const string ServerUri = "http://localhost:8888"; // SignalR服務地址
    
            /// <summary>
            /// 啟動服務
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void BtnStart_Click(object sender, EventArgs e)
            {
                BtnStart.Enabled = false;
    
                WriteToConsole("正在啟動服務...");
                Task.Run(() => { BtnStart.Enabled = !StartServer(); }); // 異步啟動SignalR服務
                 
                //Task.Run(() => StartServer()); // 異步啟動SignalR服務
                //Task.Run(() =>
                //{
                //    BtnStart.Enabled = !StartServer();
                //bool flag = StartServer();
                //BtnStart.Invoke(new Action<bool>((f) => BtnStart.Enabled = !f), flag);
    
                // }); // 異步啟動SignalR服務
    
                //BtnStart.Enabled = !StartServer();
            }
    
            /// <summary>
            /// 停止服務
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void BtnStop_Click(object sender, EventArgs e)
            {
                SignalR.Dispose();
                Close();
            }
    
    
            /// <summary>
            /// 啟動SignalR服務,將SignalR服務寄宿在WPF程序中
            /// </summary>
            private bool StartServer()
            {
                try
                {
                    SignalR = WebApp.Start(ServerUri);  // 啟動SignalR服務
                }
                catch (Exception ex)
                {
                    WriteToConsole(ex.Message);
                    return false;
                }
    
                WriteToConsole("服務已經成功啟動,地址為:" + ServerUri);
                return true;
            }
    
            private delegate void WriteToConsoleDe(string msg);
            /// <summary>
            /// 將消息添加到消息列表中
            /// </summary>
            /// <param name="message"></param>
            public void WriteToConsole(string message)
            {
                if (TxtConsole.InvokeRequired)
                {
                    TxtConsole.Invoke(new Action<string>((string msg) => TxtConsole.AppendText(message + Environment.NewLine)), message);
                    return;
                }
    
                TxtConsole.AppendText(message + Environment.NewLine);
            }
    
    
    
        }
    }

     

  • 客戶端(HTML)
  1. 創建Web空程序 SignalRWebApplication

     

  2. 添加GIT包
    Microsoft.AspNet.SignalR.JavaScript.Client

     



  3. 添加HTML頁面,命名為:SendMessage.html

  4. SendMessage代碼如下
    <!DOCTYPE html>
    <html>
    <head>
        <title>SignalR Simple Chat</title>
        <style type="text/css">
            .container {
                background-color: #99CCFF;
                border: thick solid #808080;
                padding: 20px;
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <input type="text" id="message" />
            <input type="button" id="sendmessage" value="Send" />
            <input type="hidden" id="displayname" />
            <ul id="discussion"></ul>
        </div>
        <!--Script references. -->
        <!--Reference the jQuery library. -->
        <script src="Scripts/jquery-1.6.4.min.js"></script>
        <!--Reference the SignalR library. -->
        <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
        <!--Reference the autogenerated SignalR hub script. -->
        <script src="http://localhost:8080/signalr/hubs"></script>
        <!--Add script to update the page and send messages.-->
        <script type="text/javascript">
            $(function () {
                //Set the hubs URL for the connection
                $.connection.hub.url = "http://localhost:8080/signalr";
    
                // Declare a proxy to reference the hub.
                var chat = $.connection.myHub;
    
                // Create a function that the hub can call to broadcast messages.
                chat.client.addMessage = function (name, message) {
                    // Html encode display name and message.
                    var encodedName = $('<div />').text(name).html();
                    var encodedMsg = $('<div />').text(message).html();
                    // Add the message to the page.
                    $('#discussion').append('<li><strong>' + encodedName
                        + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
                };
                // Get the user name and store it to prepend to messages.
                $('#displayname').val(prompt('Enter your name:', ''));
                // Set initial focus to message input box.
                $('#message').focus();
                // Start the connection.
                $.connection.hub.start().done(function () {
                    $('#sendmessage').click(function () {
                        // Call the Send method on the hub.
                        chat.server.send($('#displayname').val(), $('#message').val());
                        // Clear text box and reset focus for next comment.
                        $('#message').val('').focus();
                    });
                });
            });
        </script>
    </body>
    </html


  5. 源碼下載:https://pan.baidu.com/s/1bpayjT1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM