Home > Backend Development > C#.Net Tutorial > Detailed explanation of the application of Asp.net SignalR and implementation of group chat function

Detailed explanation of the application of Asp.net SignalR and implementation of group chat function

Y2J
Release: 2017-04-27 15:58:45
Original
1983 people have browsed it

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 SignalR

public class Startup
 {
 public void Configuration(IAppBuilder app)
 {
  app.MapSignalR();
 }
 }
Copy after login

and then configure the Startup class in web.config, add

appSettings node ="SignalRChat.App_Start.Startup"/>

1.2.2. Introduce SignalR js into the page

1. Since the SignalR front-end is based on jQuery, the page needs to be introduced jQuery.

2. Introduce SignalR’s js.

3. Introduce the most important hubs js. This js does not actually exist. SignalR will reflect all the methods for the client to call and put them into hubs js.

<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>
Copy after login

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)
 {
 }
 }
Copy after login

In this way, the preliminary preparation work is basically completed, and the specific operations follow.

2. Principle and simple programming

In fact, if the principle is simple to understand, it is very simple, because http is stateless, so after each request will be disconnected from the server, which means that the client can easily find the server, but it will be more troublesome if the server wants to send a message to your client. If you don’t understand, you can refer to the previous article B/S (Web) Real-time Communication solution.

SignalR solves this problem very well, which means that it realizes full-duplex communication between the browser and the server.

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>
Copy after login

Server Code

[HubName("simpleHub")]
 public class SimpleHub : Hub
 {
 public void SendMsg(string msg)
 {
  // 获取链接id
  var connectionId = Context.ConnectionId; 
  // 获取cookie
  var cookie = Context.RequestCookies;

 }

 }
Copy after login

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.

We can also get what we want in Context, such as link id, cookie, etc.

2.2. Server to client (S=>B)

Server code

[HubName("simpleHub")]
 public class SimpleHub : Hub
 {
 public void SendMsg(string msg)
 {
  Clients.All.msg("发送给客户端的消息"); 
 }
 }
Copy after login

Client Code

<script type="text/javascript">

 var ticker = $.connection.groupChatHub;
 $.connection.hub.start();

 ticker.client.msg = function (data) {
 console.log(data);
 } 
</script>
Copy after login

This demonstrates how to send messages to the client, which is also an important function of SignalR. There are two problems that need to be solved here.

Question 1. Here is a message sent to all connected clients. How should it be sent if it is a single client or a group of clients.

Question 2: When we call msg to send a message to a client, we give feedback after receiving the message, and then send the message to the client. This is very similar to ajax. The server does not actively send messages to the client. end to send messages.

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("发送给客户端的消息");
Copy after login

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().Clients to get Clients where we need to send messages. To obtain Clients and send messages, we'd better write them in singleton mode, because this requirement is very consistent with singletons, and there are detailed codes in the group chat.

3. SignalR implements group chat

The above introduction and code can already implement b=>s and s=>b, then implement it Group chat and individual chat are relatively simple.

由于功能比较简单,所有我把用户名存到了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") };
 }
 }
Copy after login

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=&#39;p&#39;>" + data.Name + ":</span>" + data.Msg + " <span class=&#39;time&#39;>" + 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(&#39;<option value="0">所有人</option>&#39;);
   for (var i = 0; i < data.length; i++) {
   $("#users").append(&#39;<option value="&#39; + data[i] + &#39;">&#39; + data[i] + &#39;</option>&#39;)
   }

  }
  });

  // 发送消息按钮
  $("#btn-send").click(function () {
  var msg = $("#txt-msg").val();
  if (!msg) {
   alert(&#39;请输入内容!&#39;); return false;
  }
  $("#txt-msg").val(&#39;&#39;);

  // 主动发送消息,传入发送给谁,和发送的内容。
  ticker.server.sendMsg($("#users").val(), msg);
  });

 });
 </script>
Copy after login

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=&#39;if (event.keyCode == 13) { $("#btn-send").click() }&#39; class="form-control" id="txt-msg" placeholder="内容" style="max-width:400px;" />
<br />
<button type="button" id="btn-send">发送</button>
Copy after login

这样就消息了群聊和发送给特定的人聊天功能。

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") });
 }
 }
Copy after login

如果需要发送消息,直接调用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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template