1. 程式人生 > 實用技巧 >利用SignalR實現聊天室(實戰篇)

利用SignalR實現聊天室(實戰篇)

簡易單網頁聊天室:

1.新增SignalR外掛包:

2.在專案下建立資料夾:MyHub

且建立類:MyHub

  1 [HubName("myHub")]
  2     public class MyHub : Hub
  3     {
  4         private IList<string> userList = UserInfo.userList;
  5         //   public readonly static Dictionary<string, string> _connections = new Dictionary<string, string>();
6 // Is set via the constructor on each creation 7 private Broadcaster _broadcaster; 8 /// <summary> 9 10 /// 靜態使用者列表 11 12 /// </summary> 13 14 15 16 public MyHub() : this(Broadcaster.Instance) 17 { 18 19 } 20 21
public MyHub(Broadcaster broadcaster) 22 { 23 _broadcaster = broadcaster; 24 25 } 26 public void Send(string msg) 27 { 28 string name = "NiHao"; 29 Clients.All.SendMessage(name, msg); 30 } 31 //客戶端連線上時,會進入到此方法中
32 public override Task OnConnected() 33 { 34 Trace.WriteLine("客戶端連線成功"); 35 return base.OnConnected(); 36 } 37 38 39 public override Task OnReconnected() 40 { 41 Trace.WriteLine("客戶端重連中"); 42 return base.OnReconnected(); 43 } 44 45 public override Task OnDisconnected(bool stopCalled) 46 { 47 return base.OnDisconnected(stopCalled); 48 } 49 public void SendLogin(string name) 50 { 51 52 if (!userList.Contains(name)) 53 { 54 55 userList.Add(name); 56 57 //這裡便是將使用者id和姓名聯絡起來 58 59 Connects._connections.Add(name, Context.ConnectionId); 60 } 61 else 62 { 63 //每次登陸id會發生變化 64 65 Connects._connections[name] = Context.ConnectionId; 66 67 } 68 UserInfo.userList = userList; 69 //新使用者上線,伺服器廣播該使用者名稱 70 71 // Clients.All.loginUser(userList); 72 73 } 74 75 private Random random = new Random(); 76 77 /// <summary> 78 /// 被動收發訊息 79 /// </summary> 80 /// <param name="name1">訊息發起者</param> 81 /// <param name="name2">訊息接收者</param> 82 public void SendByGroup(string name1, string name2, string Msg) 83 { 84 JObject json = new JObject(); 85 //Client內為使用者的id,是唯一的,SendMessage函式是前端函式,意思是伺服器將該訊息推送至前端 86 87 json.Add("A", random.Next(1000, 10000).ToString()); 88 json.Add("B", random.Next(20).ToString()); 89 90 91 Clients.Client(Connects._connections[name2]).sendMessage_Persion("來自使用者" + name1 + " " + DateTime.Now.ToString("yyyy/MM/ddhh:mm:ss") + "的訊息推送!"+Msg); 92 // Clients.Client(Connects._connections[name2]).SendMessage(json); 93 94 } 95 } 96 97 98 /// <summary> 99 /// 資料廣播器 100 /// </summary> 101 public class Broadcaster 102 { 103 private readonly static Lazy<Broadcaster> _instance = 104 new Lazy<Broadcaster>(() => new Broadcaster()); 105 106 private readonly IHubContext _hubContext; 107 108 private Timer _broadcastLoop; 109 110 public Broadcaster() 111 { 112 // 獲取所有連線的控制代碼,方便後面進行訊息廣播 113 _hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 114 // Start the broadcast loop 115 _broadcastLoop = new Timer( 116 BroadcastShape, 117 null, 118 1000, 119 1000); 120 121 } 122 123 124 private Random random = new Random(); 125 126 127 private void BroadcastShape(object state) 128 { 129 // 定期執行的方法 130 //1.查詢所有連線的PID與裝置ID 131 //2.根據裝置ID與PID查詢所屬的評分記錄 132 //3.查詢所有題目的判定條件 133 //4.對判定條件進行篩選 134 //5.合併判定條件 135 //6.對資料進行分發 136 //for (int i = 0; i < UserInfo.userList.Count; i++) 137 //{ 138 // IList<RebackModels> list = getDataServer.getSubmitLogInfo(UserInfo.userList[i].Split('_')[0], UserInfo.userList[i].Split('_')[1], UserInfo.userList[i].Split('_')[2]); 139 // _hubContext.Clients.Client(Connects._connections[UserInfo.userList[i]]).sendTest1(list); 140 //} 141 142 143 144 145 if (!Connects._connections.ContainsKey("wdd3"))//不存在 146 { 147 148 } 149 else//存在 150 { 151 _hubContext.Clients.Client(Connects._connections["wdd3"]).sendMessage123(random.Next(1000).ToString()); 152 } 153 _hubContext. Clients.All.sendMessage("當前隨機數:"+random.Next(1000).ToString()); 154 155 // _hubContext.Clients.All(random.Next(1000).ToString()); 156 } 157 public static Broadcaster Instance 158 { 159 get 160 { 161 return _instance.Value; 162 } 163 } 164 }
View Code
1 public static class Connects
2     {
3         public readonly static Dictionary<string, string> _connections = new Dictionary<string, string>();
4     }
5     public static class UserInfo
6     {
7         public static IList<string> userList = new List<string>();
8     }
View Code
 1 <div id="test">這裡即將顯示伺服器推送的資料</div>
 2 <div id="test1">這裡即將顯示伺服器推送的資料</div>
 3 <div id="test2">這裡即將顯示伺服器推送的資料</div>
 4 <input type="hidden" id="displayname" />
 5 <div>傳送人姓名<input type="text" style="width:200px" id="sendusername" /></div>
 6 <div>傳送內容:<input type="text" style="width:200px;height:100px" id="msgcontent" /></div>
 7 <input id="send" type="button" value="傳送" />
 8 <script src="~/Scripts/jquery-3.3.1.min.js"></script>
 9 <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
10 <script src="~/signalr/hubs"></script>
11 <script>
12     $(function () {
13         var mypush = $.connection.myHub;
14 
15         $('#displayname').val(prompt('請輸入暱稱:', ''))
16 
17         mypush.client.sendMessage = function (message) {
18             $("#test").text(message);
19             console.log(message);
20         };
21         mypush.client.sendMessage_Persion = function (message) {
22             $("#test2").text(message);
23             console.log(message);
24         };
25         mypush.client.sendTest1 = function (message) {
26             $("#test1").text(message);
27             console.log(message);
28             setmsg(message);
29         };
30 
31 
32         $.connection.hub.start().done(function () {
33             var username = $('#displayname').val();
34             console.log(username);
35             mypush.server.sendLogin(username);
36 
37             $('#send').click(function () {
38 
39                 var friend = $('#sendusername').val();
40                 var msgcontent = $("#msgcontent").val();
41                 //呼叫後端函式,傳送指定訊息
42 
43                 mypush.server.sendByGroup(username, friend, msgcontent);
44 
45             });
46         });
47     })
48 </script>
View Code