Getting started with SignalR simple example tutorial
I went to work at the company on the last day of last Friday and wanted to do something when I was bored. someone asked me to make a simple version of online chat, so I decided to spend a day to get a simple tutorial on SignalR and create an online chat.
1)
2: A new Hub inheritance class ChatHub is added to the MVC project. The HubName tag is similar to a RENAME.
3: The OnlineCache class defines a KEY and VALUE. It is mainly used to record the relationship between user names and keys automatically generated by Signalr.
4: Register app. MapSignalR () in Startup. cs ();
[HubName ("customhub")] public class ChatHub: hub {// <summary> /// send information /// </summary> /// <param name = ""> </param> /// <returns> </returns> public void Send (string name, string message) {Clients. all. addNewMessageToPage (name, message) ;}/// <summary> /// the page opens and is called by the client when the Signalr object is created. Then, the server lists existing users, push back the client to refresh the online user list /// </summary> /// <param name = ""> </param> /// <returns> </returns> public void Push (strin G name) {if (! OnlineCache. dicSignalrs. containsKey (base. context. connectionId) OnlineCache. dicSignalrs. add (base. context. connectionId, name); else {OnlineCache. dicSignalrs. remove (base. context. connectionId); OnlineCache. dicSignalrs. add (base. context. connectionId, name );}
/// Here, the online personnel list is pushed back to client Clients. all. subscribeUsers (name, OnlineCache. onlineToList ();} // Abstract: // Called when the connection connects to this hub instance. //// return result: // A System. threading. tasks. task public override Task OnConnected () {return base. onConnected ();} // Abstract: // Called when a connection disconnects from this hub gracefully or due to a timeout. //// parameter: // stopCalled: // true, if stop was called on the client closing the connection gracefully; false, // if the connection has been lost for longer than the Microsoft. aspNet. signalR. configuration. IConfigurationManager. disconnectTimeout. // Timeouts can be caused by clients reconnecting to another SignalR server in scaleout. //// return result: // A System. threading. tasks. task /// <summary> /// triggered offline /// </summary> /// <param name = "stopCalled"> </param> /// <returns> </returns> public override Task OnDisconnected (bool stopCalled) {if (OnlineCache. dicSignalrs. containsKey (base. context. connectionId) {var name = OnlineCache. dicSignalrs [base. context. connectionId]; OnlineCache. dicSignalrs. remove (base. context. connectionId );
/// After going offline, push the removed notifications to the Client client. all. removeUser (name, OnlineCache. onlineToList ();} return base. onDisconnected (stopCalled);} // Abstract: // Called when the connection reconnects to this hub instance. //// return result: // A System. threading. tasks. task public override Task OnReconnected () {return base. onReconnected () ;}} public class OnlineCache {public OnlineCache () {}public string Key {set; get ;}public string Value {set; get;} static OnlineCache () {if (dicSignalrs = null) dicSignalrs = new Dictionary <string, string> ();} public static Dictionary <string, string> dicSignalrs; /// <summary> /// extract list /// </summary> /// <returns> </returns> public static List <OnlineCache> OnlineToList () => dicSignalrs. select (o => new OnlineCache () {Key = o. key, Value = o. value }). toList ();}
Front-end JS script
@ {Layout = null ;}<! DOCTYPE html> // ** It is mainly used to send chat messages. server. send (vm. customname, $ ('# message '). val (); $ ('# message '). val (''). focus () ;}); vm. getOnlineUser () ;}, callbackmessage: function () {chat =$. connection. customhub;
// ** If a user logs on to the console, the message name pushed by the server is the online user name. users is the online user list and directly bound to the mvvm onlines refresh list chat. client. subscribeUsers = function (name, users) {layer. tips (name + "online", '# btnsend', {tips: [1,' # 3595CC ']}); vm. onlines = users;}; chat. client. removeUser = function (name, users) {layer. tips (name + "offline", '# btnsend', {tips: [1, 'red']}); vm. onlines = users;}; chat. client. addNewMessageToPage = function (name, message) {vm. logs. push ({name: name, message: message}) ;}; vm. connection ();}}); </script>