In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of Asp.net SignalR, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
What is Asp.net SignalR?
Asp.net SignalR is a class library used by Microsoft to realize real-time communication. In general, SignalR uses JavaScript's long polling (long polling) to achieve client-server communication. With the emergence of WebSockets in Html5, SignalR also supports WebSockets communication. In addition, the programs developed by SignalR are not only limited to hosting in IIS, but also can be hosted in any application, including console, client programs and Windows services, etc., and also support Mono, which means that it can be deployed across platforms in the Linux environment.
There are two types of objects within SignalR:
Http persistent connection (Persisten Connection) object: a function used to solve long-term connections. It is also possible for the client to actively request data from the server, and the server does not need to implement too many details, but only needs to deal with the five events provided in the PersistentConnection: OnConnected, OnReconnected, OnReceived, OnError and OnDisconnect.
Hub (hub) object: used to solve the function of real-time (realtime) information exchange. The server can use URL to register one or more Hub. As long as it connects to this Hub, it can share the information sent to the server with all clients. At the same time, the server can call the client script.
SignalR encapsulates the exchange of the whole information, and both the client and the server use JSON to communicate. All the Hub information declared on the server will generate JavaScript and output to the client, .NET relies on Proxy to generate proxy objects, and the interior of Proxy is to convert JSON into objects.
The interaction between the client and the server is shown in the following figure:
As can be seen from the above introduction, since SignalR is created for real-time, it determines where it is used. The specific application scenarios are as follows:
1. Chat rooms, such as online customer service system, IM system, etc.
2. Real-time update of stock price
3. Message push service
4. Real-time push of the position of characters in the game
At present, my company is developing an online customer service system.
Third, use Asp.net SignalR to broadcast messages on the web side.
Through the introduction of the second part, I believe you have a preliminary understanding of Asp.net SignalR, and then through two examples to deepen your understanding of the operating mechanism of SignalR. The first example is how to use SignalR to broadcast messages on the web side.
Using Visual Studio 2013, create a MVC project
Install the SignalR package through Nuget. Right reference-"Select manage Nuget package -" enter SignalR in the window that appears to find the SignalR package for installation.
After installing SignalR successfully, the script for the SignalR library will be added to the Scripts folder. It is shown in the following figure:
4. Add a SignalR hub (v2) to the project and name it ServerHub.
5. Populate the following code into the ServerHub class you just created.
Using Microsoft.AspNet.SignalR;using Microsoft.AspNet.SignalR.Hubs;using System Namespace SignalRQuickStart {public class ServerHub: Hub {private static readonly char [] Constant = {# # * * $$} {'0mm,' 1mm, '2stories,' 3bands, '4bands,' 5bands, '6bands,' 7bands, '8bands,' 9bands, 'asides,' breads, 'canals,' dudes, 'eBay,' fumes, 'gathers,' hacks, 'iTunes,' jacks,'k' "lags," masks, "nails," oaths, "packs,"Q", "rudes,"slots,"tweets,"utensils,"vaults,"wags,"x", "yearly,"zies,"A", "Bones,"clocks,"dudes,"ejaculations,"Fathers,"Gods,"hacks,"I", "J'" 'Knowles, 'Lords,' Mills, 'Oaks,' oaks, 'Qbands,' Renews, 'slots,' tweets, 'Utters,' Vaults, 'Wales,' Xrays, 'Yoshes,' Z'} / / Server code / public void Send (string message) {var name = GenerateRandomName (4) for client calls; / / call all client sendMessage methods Clients.All.sendMessage (name, message) } / generate random username function / public static string GenerateRandomName (int length) {var newRandom = new System.Text.StringBuilder (62); var rd = newRandom (); for (var I = 0; I
< length; i++) { newRandom.Append(Constant[rd.Next(62)]); } return newRandom.ToString(); } }} 6. 创建一个Startup类,如果开始创建MVC项目的时候没有更改身份验证的话,这个类会默认添加的,如果已有就不需要重复添加了。按照如下代码更新Startup类。 7. 在Home控制器中创建一个Home Action方法 public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Chat() { return View(); } } 8. 在Views文件中Home文件夹中创建一个Chat视图,视图代码如下所示: @{ ViewBag.Title = "聊天窗口";}Chat @section scripts{ $(function () { // 引用自动生成的集线器代理 var chat = $.connection.serverHub; // 定义服务器端调用的客户端sendMessage来显示新消息 chat.client.sendMessage = function (name, message) { // 向页面添加消息 $('#discussion').append('' + htmlEncode(name) + ': ' + htmlEncode(message) + ''); }; // 设置焦点到输入框 $('#message').focus(); // 开始连接服务器 $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // 调用服务器端集线器的Send方法 chat.server.send($('#message').val()); // 清空输入框信息并获取焦点 $('#message').val('').focus(); }); }); }); // 为显示的消息进行Html编码 function htmlEncode(value) { var encodedValue = $('').text(value).html(); return encodedValue; } } 9. 修改App_Start文件夹内的RoutConfig类,将Action方法默认设置为Chat. public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Chat", id = UrlParameter.Optional } ); } } 到此,我们的例子就实现完成了,接下来我们先来看看运行效果,之后再来解释到底SignalR是如何来完成广播消息的。运行的运行结果如下。 从运行结果,你可以发现,在任何一个窗口输入信息并发送,所有客户端将收到该消息。这样的效果在实际应用中很多,如QQ,一登录QQ的时候都会推送腾讯广告消息。 看完了运行结果,接下来我们来分析下代码,进而来剖析下SignalR到底是如何工作的。 按照B/S模式来看,运行程序的时候,Web页面就与SignalR的服务建立了连接,具体的建立连接的代码就是:$.connection.hub.start()。这句代码的作用就是与SignalR服务建立连接,后面的done函数表明建立连接成功后为发送按钮注册了一个click事件,当客户端输入内容点击发送按钮后,该Click事件将会触发,触发执行的操作为: chat.server.send($('#message').val())。这句代码表示调用服务端的send函数,而服务端的Send韩式又是调用所有客户端的sendMessage函数,而客户端中sendMessage函数就是将信息添加到对应的消息列表中。这样就实现了广播消息的功能了。 看到这里,有人是否会有疑问,前面的实现都只用到了集线器对象,而没有用到持久连接对象。其实并不是如此,$.connection这句代码就是使用持久连接对象,当然你也可以在重新OnConnected方法来查看监控客户端的连接情况,更新的代码如下所示: public class ServerHub : Hub { private static readonly char[] Constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /// /// 供客户端调用的服务器端代码 /// /// public void Send(string message) { var name = GenerateRandomName(4); // 调用所有客户端的sendMessage方法 Clients.All.sendMessage(name, message); } /// /// 客户端连接的时候调用 /// /// public override Task OnConnected() { Trace.WriteLine("客户端连接成功"); return base.OnConnected(); } /// /// 产生随机用户名函数 /// /// 用户名长度 /// public static string GenerateRandomName(int length) { var newRandom = new System.Text.StringBuilder(62); var rd = new Random(); for (var i = 0; i < length; i++) { newRandom.Append(Constant[rd.Next(62)]); } return newRandom.ToString(); } } 这样在运行页面的时候,将在输出窗口看到"客户端连接成功"字样。运行效果如下图所示: 在第二部分介绍的时候说道,在服务端声明的所有Hub信息,都会生成JavaScript输出到客户端,为了验证这一点,可以在Chrome中F12来查看源码就明白了,具体如下图所示: 看到上图,你也就明白了为什么Chat.cshtml页面需要引入"signalr/hubs"脚本库了吧。 四、在桌面程序中如何使用Asp.net SignalR 上面部分介绍了SignalR在Asp.net MVC 中的实现,这部分将通过一个例子来看看SignalR在WPF或WinForm是如何使用的。其实这部分实现和Asp.net MVC中非常相似,主要不同在于,Asp.net MVC中的SignalR服务器寄宿在IIS中,而在WPF中应用,我们把SignalR寄宿在WPF客户端中。 下面让我们看看SignalR服务端的实现。 /// /// 启动SignalR服务,将SignalR服务寄宿在WPF程序中 /// private void StartServer() { try { SignalR = WebApp.Start(ServerUri); // 启动SignalR服务 } catch (TargetInvocationException) { WriteToConsole("一个服务已经运行在:" + ServerUri); // Dispatcher回调来设置UI控件状态 this.Dispatcher.Invoke(() =>ButtonStart.IsEnabled = true); return;} this.Dispatcher.Invoke (() = > ButtonStop.IsEnabled = true); WriteToConsole ("Service started successfully, address:" + ServerUri);} public class ChatHub: Hub {public void Send (string name, string message) {Clients.All.addMessage (name, message) } public override Task OnConnected () {/ / Application.Current.Dispatcher.Invoke (() = > ((MainWindow) Application.Current.MainWindow) .WriteToConsole ("client connection, connection ID is:" + Context.ConnectionId); return base.OnConnected () } public override Task OnDisconnected (bool stopCalled) {Application.Current.Dispatcher.Invoke (()) = > ((MainWindow) Application.Current.MainWindow) .WriteToConsole ("client disconnects, connection ID is:" + Context.ConnectionId); return base.OnDisconnected (true) }} public class Startup {public void Configuration (IAppBuilder app) {/ / for more information about how to configure the application, visit http://go.microsoft.com/fwlink/?LinkID=316888 / / allow CORS to cross-domain / / app.UseCors (CorsOptions.AllowAll); app.MapSignalR ();}}
Through the above code, our SignalR server implementation is completed, and the implementation logic is similar to the Asp.net MVC code.
Next, let's look at how the WPF client connects and communicates with the server. The implementation of the specific client is as follows:
Public IHubProxy HubProxy {get; set;} const string ServerUri = "http://localhost:8888/signalr"; public HubConnection Connection {get; set;} public MainWindow () {InitializeComponent (); / / start connecting to the service ConnectAsync () when the window starts } / send message / private void ButtonSend_Click (object sender, RoutedEventArgs e) {/ / call the server's Send method / / server's Send method through the proxy and then call the client's AddMessage method to output the message to the message box HubProxy.Invoke ("Send", GenerateRandomName (4), TextBoxMessage.Text.Trim ()) TextBoxMessage.Text = String.Empty; TextBoxMessage.Focus ();} private async void ConnectAsync () {Connection = new HubConnection (ServerUri); Connection.Closed + = Connection_Closed; / / create a hub proxy object HubProxy = Connection.CreateHubProxy ("ChatHub") / for server calls to output messages to HubProxy.On in the message list box ("AddMessage", (name, message) = > this.Dispatcher.Invoke (() = > RichTextBoxConsole.AppendText (String.Format ("{0}: {1}\ r", name, message); try {await Connection.Start () } catch (HttpRequestException) {/ / connection failed return;} / display chat control ChatPanel.Visibility = Visibility.Visible; ButtonSend.IsEnabled = true; TextBoxMessage.Focus (); RichTextBoxConsole.AppendText ("connect to service:" + ServerUri + "\ r");}
The above code is the core code of the WPF client implementation. The main logic is that when the client starts, it calls the Connection.Start method to connect with the server. Then the Send method in the hub is called by the HubProxy proxy class, and the Send method in the hub outputs the message to the message box of the client to display by calling the addMessage method of the client, thus completing the push process of the message. Next, let's see how it works:
As can be seen from the above running effect, the effect is the same as that on Asp.net MVC.
The above is all the content of this article "sample Analysis of Asp.net SignalR". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.