


Detailed explanation of the application of Asp.net SignalR and implementation of group chat function
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
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(); } }and then configure the Startup class in web.config, add
<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>1.2.3. Create a new GroupChatHub class and inherit the Hub abstract class The method in the hub class is the js method provided to the client for calling. You can use signalr to call SendMsg in js.
[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { } }In this way, the preliminary preparation work is basically completed, and the specific operations follow.
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>Server Code
[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { // 获取链接id var connectionId = Context.ConnectionId; // 获取cookie var cookie = Context.RequestCookies; } }SimpleHub is the inherited Hub class SimpleHub we defined, and then we can rename it with the attribute HubName. Then start linking. After the link is completed, we can call the method called in the SimpleHub class. This makes it very simple to send messages from the client to the server.
2.2. Server to client (S=>B)
Server code[HubName("simpleHub")] public class SimpleHub : Hub { public void SendMsg(string msg) { Clients.All.msg("发送给客户端的消息"); } }Client Code
<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("发送给客户端的消息");These are the three more commonly used ones. Of course there are many more, such as AllExcept, Clients. Others, OthersInGroup, OthersInGroups, etc. were also added in SignalR2.0. Question 2. We can call GlobalHost.ConnectionManager.GetHubContext
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!

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)
