2021-10-19


前言

提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、SignaleR是什么?

可以简单理解为一个服务器端与客户端的双向通道。实时由服务器端将内容推送到连接的客户端,而不是让服务器等待客户端请求新的数据。

二、使用步骤

1.建立服务器端

建立winform服务器端代码如下(示例):

1.创建Winform窗体 ,命名SignalRService
2.添加新项-OWIN Startup类
在这里插入图片描述
3. 安装两个NuGet包
Microsoft.Owin.SelfHost
Microsoft.AspNet.SignalR.SelfHost

4.创建MoveTextHub类,需要继承于: Hub。在类上面添加[HubName(“getMessage”)]Hub的别名,方便前台调用

using Microsoft.AspNet.SignalR;
/*如果Hubs爆红请添加Get包
Microsoft.AspNet.SignalR.Hubs
*/
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);
    }
} 

5.设置刚刚创建的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();
        }
    }
}

6.主窗体,两个按钮,一个启动,一个停止,还有一个文本框,用于显示输出信息。

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);
        }



    }
}

!!! 当你看到这可能疑惑为什么会有两个服务端,这呢使我写案例时偷懒了,就把两个弄一起了,你可以把这个看成两个项目一个是Winform(服务端)+Mvc(客户端)+SignalR,另一个Mvc(服务端+客户端)+SignalR

建立mvc服务器端代码如下(示例):

1.创建Mvc
2.安装SignalRGet包
Microsoft.AspNet.SignalR
3.创建Hubs文件夹
并在其中新建项->SignalR->SignalR Hub Class (V2)命名MyHub
4.更新MyHub

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRChatMVC5.Hubs
{
    public class MyHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}

5.添加新项-OWIN Startup类

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRChatMVC5.Startup))]
namespace SignalRChatMVC5
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

6.在 HomeController 中添加方法 MyChat并新添视图

@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<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>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</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();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

2.建立客户端

客户端代码如下(示例):

1.创建新的MVC
2.添加GIT包
Microsoft.AspNet.SignalR.JavaScript.Client
3.添加HTML页面,命名为:SendMessage.html
代码如下:

<!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>

源码下载:[winfrom服务端mvc客户端](https://pan.baidu.com/s/1bpayjT1)

总结

这个是两项目的拼凑,可能会对阅读者产生误导,这属于我自己的理解,也转载了他人的内容,看了太多的具体都有谁的忘了,如果作者看到了,请及时联系我@我的邮箱:1850647211@qq.com//或者加我qq,记得备注哦!!!
反正记住一点它是一个双性通道,从服务端推送实时给客户端。
有不懂的可以参微软官网的SignalR指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值