This article mainly shares the Asp.net SignalR application and implements the group chat function, which has certain reference value. Interested friends can refer to it
ASP.NET SignalR is for ASP A library provided by .NET developers that simplifies the process for developers to add real-time Web functionality to applications. A real-time web feature is a feature where server code can push content to a connected client as soon as it becomes available, rather than having the server wait for the client to request new data. (From the official introduction.)
SignalR official website
-1. The reason for writing this article
is solved in the previous article B/S (Web) real-time communication In the plan, there is no detailed introduction to SignalR, so a separate article is dedicated to introducing SignalR. The focus of this article is the Hub function.
0. Let’s take a look at the final implementation first
##github.com/Emrys5/SignalRGroupChatDemo 1. Preparation
1.1. First download the SignalR package on NuGet.
1.2. Configure Owin and SignalR
1.2.1. Create a new Startup class, register SignalRpublic class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } }
<script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script> <script src="~/signalr/hubs"></script>
[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { } }
2. Principle and simple programming
2.1. Client to server (B=>S)
Client code<script type="text/javascript"> var ticker = $.connection.simpleHub; $.connection.hub.start(); $("#btn").click(function () { // 链接完成以后,可以发送消息至服务端 ticker.server.sendMsg("需要发送的消息"); }); </script>
[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { // 获取链接id var connectionId = Context.ConnectionId; // 获取cookie var cookie = Context.RequestCookies; } }
2.2. Server to client (S=>B)
Server code[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { Clients.All.msg("发送给客户端的消息"); } }
<script type="text/javascript"> var ticker = $.connection.groupChatHub; $.connection.hub.start(); ticker.client.msg = function (data) { console.log(data); } </script>
Solution:
Problem 1. Clients can send messages to a group or a client of a feature// 所有人 Clients.All.msg("发送给客户端的消息"); // 特定 cooectionId Clients.Client("connectionId").msg("发送给客户端的消息"); // 特定 group Clients.Group("groupName").msg("发送给客户端的消息");
3. SignalR implements group chat
由于功能比较简单,所有我把用户名存到了cookie里,也就说第一次进来时需要设置cookie。
还有就是在hub中要实现OnConnected、OnDisconnected和OnReconnected,然后在方法中设置用户和connectionid和统计在线用户,以便聊天使用。
hub代码
/// <summary> /// SignalR Hub 群聊类 /// </summary> [HubName("groupChatHub")] // 标记名称供js调用 public class GroupChatHub : Hub { /// <summary> /// 用户名 /// </summary> private string UserName { get { var userName = Context.RequestCookies["USERNAME"]; return userName == null ? "" : HttpUtility.UrlDecode(userName.Value); } } /// <summary> /// 在线用户 /// </summary> private static Dictionary<string, int> _onlineUser = new Dictionary<string, int>(); /// <summary> /// 开始连接 /// </summary> /// <returns></returns> public override Task OnConnected() { Connected(); return base.OnConnected(); } /// <summary> /// 重新链接 /// </summary> /// <returns></returns> public override Task OnReconnected() { Connected(); return base.OnReconnected(); } private void Connected() { // 处理在线人员 if (!_onlineUser.ContainsKey(UserName)) // 如果名称不存在,则是新用户 { // 加入在线人员 _onlineUser.Add(UserName, 1); // 向客户端发送在线人员 Clients.All.publshUser(_onlineUser.Select(i => i.Key)); // 向客户端发送加入聊天消息 Clients.All.publshMsg(FormatMsg("系统消息", UserName + "加入聊天")); } else { // 如果是已经存在的用户,则把在线链接的个数+1 _onlineUser[UserName] = _onlineUser[UserName] + 1; } // 加入Hub Group,为了发送单独消息 Groups.Add(Context.ConnectionId, "GROUP-" + UserName); } /// <summary> /// 结束连接 /// </summary> /// <param name="stopCalled"></param> /// <returns></returns> public override Task OnDisconnected(bool stopCalled) { // 人员链接数-1 _onlineUser[UserName] = _onlineUser[UserName] - 1; // 判断是否断开了所有的链接 if (_onlineUser[UserName] == 0) { // 移除在线人员 _onlineUser.Remove(UserName); // 向客户端发送在线人员 Clients.All.publshUser(_onlineUser.Select(i => i.Key)); // 向客户端发送退出聊天消息 Clients.All.publshMsg(FormatMsg("系统消息", UserName + "退出聊天")); } // 移除Hub Group Groups.Remove(Context.ConnectionId, "GROUP-" + UserName); return base.OnDisconnected(stopCalled); } /// <summary> /// 发送消息,供客户端调用 /// </summary> /// <param name="user">用户名,如果为0,则是发送给所有人</param> /// <param name="msg">消息</param> public void SendMsg(string user, string msg) { if (user == "0") { // 发送给所有用户消息 Clients.All.publshMsg(FormatMsg(UserName, msg)); } else { //// 发送给自己消息 //Clients.Group("GROUP-" + UserName).publshMsg(FormatMsg(UserName, msg)); //// 发送给选择的人员 //Clients.Group("GROUP-" + user).publshMsg(FormatMsg(UserName, msg)); // 发送给自己消息 Clients.Groups(new List<string> { "GROUP-" + UserName, "GROUP-" + user }).publshMsg(FormatMsg(UserName, msg)); } } /// <summary> /// 格式化发送的消息 /// </summary> /// <param name="name"></param> /// <param name="msg"></param> /// <returns></returns> private dynamic FormatMsg(string name, string msg) { return new { Name = name, Msg = HttpUtility.HtmlEncode(msg), Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }; } }
js代码
<script type="text/javascript"> $(function () { // 链接hub var ticker = $.connection.groupChatHub; $.connection.hub.start(); // 接收服务端发送的消息 $.extend(ticker.client, { // 接收聊天消息 publshMsg: function (data) { $("#msg").append("<li><span class='p'>" + data.Name + ":</span>" + data.Msg + " <span class='time'>" + data.Time + "</span></li>") $("#msg").parents("p")[0].scrollTop = $("#msg").parents("p")[0].scrollHeight; }, // 接收在线人员,然后加入Select,以供单独聊天选中 publshUser: function (data) { $("#count").text(data.length); $("#users").empty(); $("#users").append('<option value="0">所有人</option>'); for (var i = 0; i < data.length; i++) { $("#users").append('<option value="' + data[i] + '">' + data[i] + '</option>') } } }); // 发送消息按钮 $("#btn-send").click(function () { var msg = $("#txt-msg").val(); if (!msg) { alert('请输入内容!'); return false; } $("#txt-msg").val(''); // 主动发送消息,传入发送给谁,和发送的内容。 ticker.server.sendMsg($("#users").val(), msg); }); }); </script>
html代码
<h2> 群聊系统(<span id="count">1</span>人在线):@ViewBag.UserName </h2> <p style="overflow:auto;height:300px"> <ul id="msg"></ul> </p> <select id="users" class="form-control" style="max-width:150px;"> <option value="0">所有人</option> </select> <input type="text" onkeydown='if (event.keyCode == 13) { $("#btn-send").click() }' class="form-control" id="txt-msg" placeholder="内容" style="max-width:400px;" /> <br /> <button type="button" id="btn-send">发送</button>
这样就消息了群聊和发送给特定的人聊天功能。
3.1、封装主动发送消息的单例
/// <summary> /// 主动发送给用户消息,单例模式 /// </summary> public class GroupChat { /// <summary> /// Clients,用来主动发送消息 /// </summary> private IHubConnectionContext<dynamic> Clients { get; set; } private readonly static GroupChat _instance = new GroupChat(GlobalHost.ConnectionManager.GetHubContext<GroupChatHub>().Clients); private GroupChat(IHubConnectionContext<dynamic> clients) { Clients = clients; } public static GroupChat Instance { get { return _instance; } } /// <summary> /// 主动给所有人发送消息,系统直接调用 /// </summary> /// <param name="msg"></param> public void SendSystemMsg(string msg) { Clients.All.publshMsg(new { Name = "系统消息", Msg = msg, Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }); } }
如果需要发送消息,直接调用SendSystemMsg即可。
GroupChat.Instance.SendSystemMsg("消息");
4、结语
啥也不说了直接源码
github.com/Emrys5/SignalRGroupChatDemo
The above is the detailed content of Detailed explanation of the application of Asp.net SignalR and implementation of group chat function. For more information, please follow other related articles on the PHP Chinese website!