Asp.net uses SignalR to implement chat room functions

高洛峰
Release: 2016-12-24 14:20:38
Original
1837 people have browsed it

1. Introduction
In the previous article "Asp.net uses SignalR to implement cool end-to-end chat function", I introduced to you how to implement the end-to-end chat function. In this article, I will Like how you use SignalR to implement functions such as group chat.

2. Implementation Ideas
To implement the group chat function, first we need to create a room, and then each online user can join this room for group chat. We can set a unique name for the room as an identifier. Is there such an existing method in the SignalR class library? The answer is yes.

// IGroupManager接口提供如下方法 // 作用:将连接ID加入某个组 // Context.ConnectionId 连接ID,每个页面连接集线器即会产生唯一ID // roomName分组的名称 Groups.Add(Context.ConnectionId, roomName); // 作用:将连接ID从某个分组移除 Groups.Remove(Context.ConnectionId, roomName); // IHubConnectionContext接口提供了如下方法 // 调用客户端方法向房间内所有用户群发消息 // Room:分组名称 // new string[0]:过滤(不发送)的连接ID数组 Clients.Group(Room, new string[0]).clientMethod
Copy after login


  The above code is the core method of implementing group chat. To put it bluntly, the Groups object is just a list object maintained by the SignalR class library. In fact, we can maintain a Dictionary > object by ourselves. When creating a room, we add the room name and enter the room. The ConnectionId of the client is added to this dictionary, and then when clicking to send a message in the chat room, we find all the ConnectionIds that join the group chat based on the room name, and then call the Clients.Clients(IList connectionIds) method to send the message Broadcast to every client. The above is the principle of implementing a chat room.

3. Use SignalR to implement the chat room function
After clarifying the implementation ideas, let’s take a look at the specific implementation code. At the same time, you can also compare the code to compare the previous implementation ideas.
First, let’s look at the implementation code of the entity class involved in the chat room function:

///  /// 用户类 ///  public class User { ///  /// 用户Id ///  public string UserId { get; set; } ///  /// 用户的连接集合 ///  public List Connections { get; set; } ///  /// 用户房间集合,一个用户可以加入多个房间 ///  public List Rooms { get; set; } public User() { Connections = new List(); Rooms = new List(); } } public class Connection { //连接ID public string ConnectionId { get; set; } //用户代理 public string UserAgent { get; set; } //是否连接 public bool Connected { get; set; } } ///  /// 房间类 ///  public class ChatRoom { // 房间名称 public string RoomName { get; set; } // 用户集合 public List Users { get; set; } public ChatRoom() { Users = new List(); } } ///  /// 上下文类,用来模拟EF中的DbContext ///  public class ChatContext { public List Users { get; set; } public List Connections { get; set; } public List Rooms { get; set; } public ChatContext() { Users = new List(); Connections = new List(); Rooms = new List(); } }
Copy after login



2. Next, let’s see the implementation of the hub:

[HubName("chatRoomHub")] public class GroupsHub : Hub { public static ChatContext DbContext = new ChatContext(); #region IHub Members // 重写Hub连接事件 public override Task OnConnected() { // 查询用户 var user = DbContext.Users.FirstOrDefault(u => u.UserId == Context.ConnectionId); if (user == null) { user = new User { UserId = Context.ConnectionId }; DbContext.Users.Add(user); } // 发送房间列表 var items = DbContext.Rooms.Select(p => new {p.RoomName}); Clients.Client(this.Context.ConnectionId).getRoomList(JsonHelper.ToJsonString(items.ToList())); return base.OnConnected(); } // 重写Hub连接断开的事件 public override Task OnDisconnected(bool stopCalled) { // 查询用户 var user = DbContext.Users.FirstOrDefault(u => u.UserId == Context.ConnectionId); if (user != null) { // 删除用户 DbContext.Users.Remove(user); // 从房间中移除用户 foreach (var item in user.Rooms) { RemoveUserFromRoom(item.RoomName); } } return base.OnDisconnected(stopCalled); } #endregion #region Public Methods // 为所有用户更新房间列表 public void UpdateRoomList() { var itme = DbContext.Rooms.Select(p => new {p.RoomName}); var jsondata = JsonHelper.ToJsonString(itme.ToList()); Clients.All.getRoomlist(jsondata); } ///  /// 加入聊天室 ///  public void JoinRoom(string roomName) { // 查询聊天室 var room = DbContext.Rooms.Find(p => p.RoomName == roomName); // 存在则加入 if (room == null) return; // 查找房间中是否存在此用户 var isExistUser = room.Users.FirstOrDefault(u => u.UserId == Context.ConnectionId); // 不存在则加入 if (isExistUser == null) { var user = DbContext.Users.Find(u => u.UserId == Context.ConnectionId); user.Rooms.Add(room); room.Users.Add(user); // 将客户端的连接ID加入到组里面 Groups.Add(Context.ConnectionId, roomName); //调用此连接用户的本地JS(显示房间) Clients.Client(Context.ConnectionId).joinRoom(roomName); } else { Clients.Client(Context.ConnectionId).showMessage("请勿重复加入房间!"); } } ///  /// 创建聊天室 ///  ///  public void CreateRoom(string roomName) { var room = DbContext.Rooms.Find(a => a.RoomName == roomName); if (room == null) { var cr = new ChatRoom { RoomName = roomName }; //将房间加入列表 DbContext.Rooms.Add(cr); // 本人加入聊天室 JoinRoom(roomName); UpdateRoomList(); } else { Clients.Client(Context.ConnectionId).showMessage("房间名重复!"); } } public void RemoveUserFromRoom(string roomName) { //查找房间是否存在 var room = DbContext.Rooms.Find(a => a.RoomName == roomName); //存在则进入删除 if (room == null) { Clients.Client(Context.ConnectionId).showMessage("房间名不存在!"); return; } // 查找要删除的用户 var user = room.Users.FirstOrDefault(a => a.UserId == Context.ConnectionId); // 移除此用户 room.Users.Remove(user); //如果房间人数为0,则删除房间 if (room.Users.Count <= 0) { DbContext.Rooms.Remove(room); } Groups.Remove(Context.ConnectionId, roomName); //提示客户端 Clients.Client(Context.ConnectionId).removeRoom("退出成功!"); } ///  /// 给房间内所有的用户发送消息 ///  /// 房间名 /// 信息 public void SendMessage(string room, string message) { // 调用房间内所有客户端的sendMessage方法 // 因为在加入房间的时候,已经将客户端的ConnectionId添加到Groups对象中了,所有可以根据房间名找到房间内的所有连接Id // 其实我们也可以自己实现Group方法,我们只需要用List记录所有加入房间的ConnectionId // 然后调用Clients.Clients(connectionIdList),参数为我们记录的连接Id数组。 Clients.Group(room, new string[0]).sendMessage(room, message + " " + DateTime.Now); } #endregion }
Copy after login



3. Above The code implementation of the SignalR server has been completed. Next, let us take a look at the implementation of the client view:

@{ Layout = null; }     Index       

名称:

输入房间名:

房间列表

    Copy after login


    4. After the above 3 steps, the chat room function has been completed. Let’s look at the specific effects. Previously, a helper code was attached here:

    ///  /// JSON 帮助类 ///  public class JsonHelper { ///  /// 从一个对象信息生成Json字符串 ///  ///  ///  public static string ToJsonString(object obj) { return JsonConvert.SerializeObject(obj); } ///  /// 从Json字符串生成对象 ///  ///  ///  ///  public static T ToObject(string jsonString) { return JsonConvert.DeserializeObject(jsonString); } }
    Copy after login


    IV. Operation results

    Next, let’s take a look at the operation effect of the chat room function. The specific operation effect is shown in the figure below:

    Asp.net uses SignalR to implement chat room functions

    At this point, all the content of this article has been introduced. Next, I will write an article about how to use SignalR to realize the function of sending pictures.

    For more articles related to Asp.net using SignalR to implement chat room functions, please pay attention to 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
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!