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
原文地址:https://www.cnblogs.com/ypeuee/p/8184786.html