SignalR Self host multi-port message Push service instance (iii)

Source: Internet
Author: User
This article is mainly for you to introduce the SIGNALR self HOST+MVC and other multi-terminal message push service, with a certain reference value, interested in small partners can refer to

I. Overview

As a result of the project needs, recently the company project has a module function, need to use to immediately get approval notice; The original design is to use Ajax to the server timed polling query, just start data volume and use of a small time fortunately, later use of the increase in the system and the complexity of various business increased, Server pressure is also growing, so I want to use a message push to replace the Ajax polling query, when there is an approval submission, call the push method, push the message to the next approver, which reduces the pressure on the server.

Signal is one of the Microsoft supported running on. The HTML websocket Framework on the net platform. Its main purpose is to implement the server to actively push the message to the client page, so that the client does not have to resend the request or use polling technology to obtain the message. And SIGNALR compatibility is also very powerful, here is not many words. Now that you've chosen signalr, start doing it!

My idea is to signalr into a self-hosted service, and our B/s project separation, the advantage is that 1, the push service is not dependent on IIS, even if IIS is hung, our push service can also run normally, 2, we can call this push service on multiple platforms, Multiple projects can be used at the same time;

Second, create the service side

Needless to say, I am also the first time to write a blog, the introduction of business scenarios and ideas, we began to code it.

1. Create a solution called "signalrproject" with vs;

2. Create a new console named server under the Signalrproject solution

3. In the Package Manager console, enter the following command


Install-package Microsoft.AspNet.SignalR.SelfHost

4. Enter the following command:


Install-package Microsoft.Owin.Cors

5. Add the UserInfo class in the server console with the following code


Using System;  namespace Server {public  class UserInfo  {public   string ConnectionID {get; set;}   public string UserName {get; set;}   Public DateTime lastlogintime {get; set;}  } }

6. Add the Chathub class in the server console with the following code


Using microsoft.aspnet.signalr;using microsoft.aspnet.signalr.hubs;using system;using System.Collections.Generic;  Using system.linq;using system.threading.tasks;namespace server{[Hubname ("Imhub")] public class Chathub:hub {//static properties public static list<userinfo> onlineusers = new list<userinfo> (); Online user list//<summary>//Login///</summary>//<param name= "userId" > User id</param>///&LT ;p Aram Name= "UserName" > User name </param> public void Register (string userName) {var connnectid = Context.connectio   NId; if (onlineusers.count (x = X.connectionid = = Connnectid) = = 0) {if (onlineusers.any (x = = X.username = Usernam e) {var items = onlineusers.where (x = X.username = = UserName).     ToList (); foreach (var item in items) {clients.allexcept (Connnectid). onuserdisconnected (item. ConnectionID, item.     UserName);    } onlineusers.removeall (x = X.username = = UserName); }//Add online personnel onlineusers.add (nEW UserInfo {ConnectionID = Connnectid, UserName = UserName, lastlogintime = DateTime.Now});  }//All clients synchronize Online user Clients.All.onConnected (Connnectid, UserName, onlineusers); }///<summary>//Send private chat///</summary>//<param name= "Touserid" > Recipient user Connection Id</param>//< param name= "message" > Content </param> public void Sendprivatemessage (string tousername, String message) {var FROMC   Onnectionid = Context.connectionid;   var touser = onlineusers.firstordefault (x = X.username = = tousername);   var fromuser = onlineusers.firstordefault (x = X.connectionid = = Fromconnectionid);    if (touser! = null) {clients.client (Touser.connectionid). Receiveprivatemessage (fromuser.username, message);   Clients.client (Touser.connectionid). Receiveprivatemessage (message);   } else {//indicates that the other party is not online Clients.Caller.absentSubscriber (); }} public void Send (string name, String message) {//clients.all {get;}//On behalf of all clients//clientS.allexcept (params string[] excludeconnectionids); Except for all client//clients.client (string ConnectionID) in the parameter; A particular client, this method is our key//clients.clients for end-to-end chat (ilist<string> connectionids); The client//clients.group in the parameter (string groupName, params string[] excludeconnectionids); Specify the client group, this is also the key to achieve group chat//clients.groups (ilist<string> groupnames, params string[] excludeconnectionids); The client group//clients.user in the parameter (string userId); Specific user//clients.users (ilist<string> userids);   The user Console.WriteLine in the parameters ("connectionid:{0}, Invokemethod:{1}", Context.connectionid, "Send");  Clients.All.addMessage (name, message); }///<summary>////</summary>//<returns></returns> public override Task Onconne   CTED () {Console.WriteLine ("Client connection, connection ID: {0}, current online number is {1}", Context.connectionid, onlineusers.count+1); Return base.  Onconnected (); }///<summary>////</summary>//<param name= "stopcalled" ></param>//<returns></returns> public override Task ondisconnected (bool stopcalled) {var user = Onlineusers.firstord   Efault (U = u.connectionid = = Context.connectionid); Determine if the user exists, or delete if (user = = null) {return base.   Ondisconnected (stopcalled); } Clients.All.onUserDisconnected (user. ConnectionID, user. UserName);   Call client user offline notification//delete user onlineusers.remove (username);   Console.WriteLine ("Client disconnected, connection ID: {0}, current online number is {1}", Context.connectionid, Onlineusers.count); Return base.  Ondisconnected (stopcalled); public override Task onreconnected () {return base.  Onreconnected (); } }}

7, add the Startup class in the server console, the code is as follows


Using microsoft.owin.cors;using owin;namespace server{public class Startup {public  void Configuration (Iappbuilder App)  {   //allow cors to cross-domain   app. Usecors (Corsoptions.allowall);   App. MAPSIGNALR ();  } }}

8, modify the server console to add program class, the code is as follows


Using microsoft.owin.hosting;using System;namespace server{class Program {  static void Main (string[] args)  { C8/>string url = "http://localhost:10086";//Set SignalR hub Server external interface   using (Webapp.start (URL))//start SignalR Hub Ser Ver   {    Console.WriteLine ("Server running on {0}", url);    Console.ReadLine ();   }  } }}

9, F5 run up

Then access the http://localhost:10086/signalr/hubs in the browser

The results are as follows:

See the content is basically completed, today, first talk about, time is not early, first rest, followed by time will be later on the article.

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.