Asp.net uses SignalR to implement cool end-to-end chat, while signalr is cool

Source: Internet
Author: User

Asp.net uses SignalR to implement cool end-to-end chat, while signalr is cool

I. Introduction
The previous article has introduced SignalR in detail and briefly introduced its application in Asp.net MVC and WPF. In the previous blog, we introduced the implementation of group messaging. However, for SignalR, it was born for real-time chat. Naturally, there were fewer end-to-end chats like QQ. This blog article describes how to use SignalR to implement functions similar to QQ chat.

Ii. Use SignalR to implement end-to-end chat
Before introducing the specific implementation, I will first introduce the idea of using SignalR to implement end-to-end chat. I believe that you have seen code like Clients. All. sendMessage (name, message) in the previous article, which indicates calling SendMessage of All Clients. The hub of SignalR enables real-time communication between the client and the server. To achieve end-to-end chat, you naturally cannot send messages like all clients, but you can only send messages to specific clients. Otherwise, you will not be confused and have no right to privacy. How can I send messages to a specific client? This problem is also the key to implementing the client-to-end chat function.

In addition to the All attribute, the client object has other attributes. You can press F12 in VS to view All the attributes or methods of the Clients object. The specific definitions are as follows:

Public interface IHubConnectionContext <T> {T All {get;} // represents All clients T AllExcept (params string [] excludeConnectionIds ); // except all clients in the parameter T Client (string connectionId); // specific clients, this method is the key T Clients (IList <string> connectionIds) for implementing peer-to-peer chat. // The client T Group (string groupName, params string [] excludeConnectionIds); // specifies the client group, which is also the key to implementing group chat. T Groups (IList <string> groupNames, params string [] excludeConnectionIds ); T User (string userId); // The User T Users (IList <string> userIds); // the User in the parameter}

In SignalR, every client marks its uniqueness, and SignalR assigns it a ConnnectionId, so that we can find a specific client through the ConnnectionId. In this way, when we send a message to a client, in addition to passing in the message, we also need to input the ConnectionId sent to the other party, in this way, the server can forward the corresponding message to the corresponding client based on the input ConnectionId. This completes the end-to-end chat function. In addition, if the user is not online, the server can save the message to the database. When the corresponding client is online, check whether the client has any messages to push from the database, if yes, extract the data from the database and push the data to the client. (However, the function of caching data on the server is not implemented in this blog. Here we will introduce the implementation principle of QQ ).

Next we will sort out the Implementation ideas of the peer chat function:

When the client logs on, it records the ConnnectionId of the client and adds the user to a static array. This data is used to record all online users.
Users can click chat among online users. When sending a message, they must pass the ConnectionId to the server.
The server calls the Clients. Client (connnection). sendMessage Method Based on the incoming message content and ConnectionId to forward the message to the corresponding Client.
Iii. Core code for implementing the cool chat function
With the implementation idea, the implementation function will be handy. Next, let's take a look at the code in the hub ChatHub:

Public class ChatHub: Hub {// static attribute public static List <UserInfo> OnlineUsers = new List <UserInfo> (); // online user list /// <summary> /// logon link // </summary> /// <param name = "userId"> User ID </param>/ // <param name = "userName"> User name </param> public void Connect (string userId, string userName) {var connnectId = Context. connectionId; if (OnlineUsers. count (x => x. connectionId = connnectId) = 0) {if (OnlineUsers. Any (x => x. userId = userId) {var items = OnlineUsers. where (x => x. userId = userId ). toList (); foreach (var item in items) {Clients. allExcept (connnectId ). onUserDisconnected (item. connectionId, item. userName);} OnlineUsers. removeAll (x => x. userId = userId);} // Add online staff OnlineUsers. add (new UserInfo {ConnectionId = connnectId, UserId = userId, UserName = userName, LastLoginTime = DateTime. now });} // All Clients synchronize online user Clients. all. onConnected (connnectId, userName, OnlineUsers );} /// <summary> /// send private chat /// </summary> /// <param name = "toUserId"> receiver user connection ID </param> /// <param name = "message"> content </param> public void SendPrivateMessage (string toUserId, string message) {var fromUserId = Context. connectionId; var toUser = OnlineUsers. firstOrDefault (x => x. connectionId = toUserId); var fromUser = Online Users. FirstOrDefault (x => x. ConnectionId = fromUserId); if (toUser! = Null & fromUser! = Null) {// send to Clients. client (toUserId ). descrieprivatemessage (fromUserId, fromUser. userName, message); // send to caller user // Clients. caller. sendPrivateMessage (toUserId, fromUser. userName, message);} else {// indicates that the other party is not online Clients. caller. absentSubscriber ();}} /// <summary> /// call when disconnection occurs /// </summary> /// <param name = "stopCalled"> </param> /// <returns> </returns> public override Task OnDisconnected (bool stopCalled) {var user = OnlineUsers. firstOrDefault (u => u. connectionId = Context. connectionId); // determines whether the user exists. if (user = null) return base is deleted if (user = null) exists. onDisconnected (stopCalled); Clients. all. onUserDisconnected (user. connectionId, user. userName); // call the client user offline notification // Delete the user OnlineUsers. remove (user); return base. onDisconnected (stopCalled );}}

The above is the main implementation of the server. Next let's look at the implementation code of the client:

<Script type = "text/javascript"> var systemHub = $. connection. chatHub;/connect to the IM server. // update the online user systemHub. client. onConnected = function (id, userName, allUsers) {var node = chatCore. node, myf = node. list. eq (0), str = '', I = 0; myf. addClass ('loading'); onlinenum = allUsers. length; if (onlinenum> 0) {str + = '<li class = "ChatCore_parentnode ChatCore_liston">' + '

The above only lists some core code implementations. In addition, a Jquery plug-in: layer is used to achieve the cool effect. The official website is http://layer.layui.com /. This plug-in is mainly used to implement the pop-up box and pop-up layer effects. To implement cool chat effects, you need to write your own JS Code. As I am not very familiar with the front-end, therefore, this JS special effect code is also based on the implementation on the network. If you want to run the command to view the effect, we recommend that you download the source code at the end of the article to run the command.

Iv. Final Results
After introducing the Implementation ideas and implementation code, it's just a very exciting moment for us to see if our implementation functions can meet our needs. In addition to meeting basic chat functions, you also need to check whether the interface is cool.

V. Summary
After reading the above results, Is it amazing. At this point, the content of this article is over. In the next article, I will continue to introduce how to use Asp.net SignalR to implement chat room functions.

Articles you may be interested in:
  • Simple Chat Room program written by ASP. NET using application and session Object
  • Use the SignalR PUSH Service to implement SignalA in Android
  • Design and Implementation of ASP. NET Website chat rooms (section 3rd)
  • Asp.net SignalR Quick Start

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.