


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(); } }
<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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



1. Find and open the WeChat software on your phone. 2. Click on the group chat where the person needs to be removed from the group to enter the chat page. 3. Click [...] in the upper right corner of the chat page. 4. Swipe down to find and click the [-] behind the group members.

When using QQ, a social software, other users can add themselves as friends through group chats. Let me introduce to you how to set up and enable adding me as a friend through group chat. After entering the mobile QQ interface, click on the personal avatar in the upper left corner to open the menu page, and then click on the "Settings" function in the lower left corner of the page to enter the setting interface. 2. After coming to the settings page, click on the "Privacy" item to select. 3. Next, there is a "How to add me as a friend" on the privacy page, click on it to enter. 4. On the new page, you will see a list of options under "You can add me as a friend in the following ways". Click the corresponding switch button behind "Group Chat". When the button is set to blue, it means it is turned on, and other users can find themselves in the group chat.

Baidu Netdisk provides file saving and sharing functions. In addition, it also hides many other practical functions to meet the diverse needs of users. Among them, communicating and discussing through Baidu Netdisk, adding friends or joining group chats, and sharing files with others are all reasons for its popularity. So how to add a group chat in the Baidu Netdisk app? Users who want to know, please come and follow this article to learn more! How to join a group on Baidu Netdisk? 1. Open Baidu Netdisk and click Share. 2. Click the plus icon in the upper right corner. 3. Click to add friends/group. 4. Enter the group number to search and click to join.

1. Open the WeChat app, click the search icon in the upper right corner, and enter your WeChat nickname. 2. The system will automatically display the various group chats the user is in. Click the [More Group Chats] button to view all the group chats you have joined. 3. Users can search for group chats that have not been found before in all group chats.

With the rapid development of mobile Internet, real-time communication has gradually become a very important requirement. In real-time communication, the most basic requirement is real-time data communication, which requires the server to be able to send data to the client in real time and interact in real time. PHP and SignalR are two very powerful tools when it comes to implementing real-time data communication. PHP is a very popular development language that can be used to write server-side code, while SignalR is a real-time communication framework that can be used to implement real-time data communication.

Amap software not only provides accurate navigation services, but also brings group chat functions to users, making travel more convenient and interesting. In Amap, you can easily create your own group chat, or choose to join an existing group chat. However, many users may not know exactly how to open a group chat in the Amap app, so the following article will provide you with a detailed introduction. For those who don’t know yet, please come and read along with this article! How to open the Amap group chat? Answer: [Amap] - [Message] - [Group Chat]. Specific steps: 1. First open the Amap software. After entering, you can see the home page, nearby, messages, taxis, and mine at the bottom. Click [Message] here; 2. Then we click on the message page.

1. First, click to enter the DingTalk software on your mobile phone. 2. Then click to enter the group chat you created. 3. Then click the three small dots in the upper right corner of the group chat page.

1. The group chat will automatically pop up under the order after we purchase the goods from the store. 2. Subsequent messages will be displayed in the [Message] column at the bottom of the page. 3. Select a group chat to enter and click the character image button in the upper right corner. 4. Here you can see all the relevant information of the group chat. Click the button on the right side of [Message Do Not Disturb] to turn off the new message reminder. But when merchants issue coupons, they will remind everyone in time.
