SignalR的簡單實現消息廣播


之前由於一個項目的需要(簡單說一下,一個網頁游戲,裁判的頁面點擊開始按鈕,玩家便可以開始游戲),研究了很久,最終一個同事跟我推薦了SignalR。距離項目結束已經有一段時間了,再來回顧一下SignalR的簡單實現吧。

1.什么 SignalR?

  ASP.NET SignalR 是為.NET 開發者提供即時通訊Web 應用的類庫。即時通訊Web服務就是服務器將內容自動推送到已經連接的客戶端,而不是服務器等待客戶端發起一個新的數據請求。簡單來說,就是實現即時通信的功能,里面很多的功能都已經封裝好了,只需要配置相關的功能即可,然后通過js實現功能。

2.Singal的代碼實現

  1.首先在VS中創建一個MVC項目

       2.通過NuGet安裝SignalR的包並引用到項目

       

  3.成功安裝后,會在Scripts文件夾下面添加JS腳本庫

  

  4.向項目中添加一個SignalR集線器(v2)並命名為ServerHub。

  

  5.將如下代碼寫入到剛剛添加的ServerHub類中:

  
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Microsoft.AspNet.SignalR;
 6 
 7 namespace SignalRDemo
 8 {
 9     public class ServerHub : Hub
10     {
11         private static readonly char[] Constant =
12         {
13             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
14             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
15             'w', 'x', 'y', 'z',
16             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
17             'W', 'X', 'Y', 'Z'
18         };
19 
20         /// <summary>
21         /// 供客戶端調用的服務器端代碼
22         /// </summary>
23         /// <param name="message"></param>
24         public void Send(string message)
25         {
26             var name = GenerateRandomName(4);
27 
28             // 調用所有客戶端的sendMessage方法
29             Clients.All.sendMessage(name, message);
30         }
31 
32         /// <summary>
33         /// 產生隨機用戶名函數
34         /// </summary>
35         /// <param name="length">用戶名長度</param>
36         /// <returns></returns>
37         public static string GenerateRandomName(int length)
38         {
39             var newRandom = new System.Text.StringBuilder(62);
40             var rd = new Random();
41             for (var i = 0; i < length; i++)
42             {
43                 newRandom.Append(Constant[rd.Next(62)]);
44             }
45             return newRandom.ToString();
46         }
47     }
48 }
View Code

  6.將如下代碼覆蓋原有的Startup的類中:

  
 1 using Microsoft.Owin;
 2 using Owin;
 3 
 4 [assembly: OwinStartupAttribute(typeof(SignalRDemo.Startup))]
 5 namespace SignalRDemo
 6 {
 7     public partial class Startup
 8     {
 9         #region MyRegion
10         public void Configuration(IAppBuilder app)
11         {
12             app.MapSignalR();
13             ConfigureAuth(app);
14         }
15         #endregion
16     }
17 }
View Code

  7.在Home控制器創建一個Chat Action方法:

  
1 public ActionResult Chat()
2         {
3             return View();
4         }
ActionResult Chat

  8.在Views中創建Chat視圖,文件代碼如下:

  
 1 @{
 2     ViewBag.Title = "Chat";
 3 }
 4 
 5 <h2>Chat</h2>
 6 
 7 <div class="container">
 8     <input type="text" id="message" />
 9     <input type="button" id="sendmessage" value="Send" />
10     <input type="hidden" id="displayname" />
11     <ul id="discussion"></ul>
12 </div>
13 
14 @section scripts
15 {
16     <!--引用SignalR庫. -->
17     <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
18     <!--引用自動生成的SignalR 集線器(Hub)腳本.在運行的時候在瀏覽器的Source下可看到 -->
19     <script src="~/signalr/hubs"></script>
20     <script>
21         $(function () {
22             // 引用自動生成的集線器代理
23             var chat = $.connection.serverHub;
24             // 定義服務器端調用的客戶端sendMessage來顯示新消息
25 
26             chat.client.sendMessage = function (name, message) {
27                 // 向頁面添加消息
28                 $('#discussion').append('<li><strong>' + htmlEncode(name)
29                     + '</strong>: ' + htmlEncode(message) + '</li>');
30                 //if (message == "1") {
31                 //    alert('已收到消息' + message);
32                 //}
33             };
34             // 設置焦點到輸入框
35             $('#message').focus();
36             // 開始連接服務器
37             $.connection.hub.start().done(function () {
38                 $('#sendmessage').click(function () {
39                     // 調用服務器端集線器的Send方法
40                     chat.server.send($('#message').val());
41                     // 清空輸入框信息並獲取焦點
42                     $('#message').val('').focus();
43                 });
44             });
45         });
46 
47         // 為顯示的消息進行Html編碼
48         function htmlEncode(value) {
49             var encodedValue = $('<div />').text(value).html();
50             return encodedValue;
51         }
52     </script>
53 }
Chat.cshtml

  9.將App_Start下面的RouteConfig文件做如下修改,以便程序運行時直接打開Chat頁面:

  

  10.運行程序,然后打開兩個窗口,即可得到如下運行結果:

  

 

3.結束語

  正是由於項目的需要,讓我無意中學習了這個SignalR,個人覺得,真的是非常好用。至於底層的具體實現,以及如何在客戶端中使用,推薦閱讀:https://www.cnblogs.com/aaaaq/p/5929104.html,我的項目Demo亦是借鑒於此。


免責聲明!

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



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