In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of SignalR Self Host+MVC and other multi-end message push services, which has a certain reference value. Interested friends can refer to it. I hope you will learn a lot after reading this article. Let's take a look at it.
I. Overview
Due to the needs of the project, recently there is a module function in the company's project, which needs to be immediately notified of approval. The original design scheme is to use ajax to conduct a regular polling query on the server, which is fine at the beginning when the amount of data and usage is small, but later, with the increase in usage and the complexity of various services in the system, the pressure on the server is increasing, so I want to use message push to replace the ajax polling query. When there is an approval submission, call the push method to push the message to the next approver. This reduces the pressure on the server.
Signal is a html websocket framework supported by Microsoft that runs on the. Net platform. The main purpose of it is to enable 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 get the message. And the compatibility of SignalR is also very strong, so I won't say much here. Now that you have chosen SignalR, let's get started!
My idea is to make SignalR into a self-hosted service, which is separated from our bstroke project. The advantage is that: 1. The push service does not depend on iis, even if iis is dead, our push service can still run normally; 2. We can call this push service on multiple platforms, and multiple projects can be used at the same time.
Create a server
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 to the Server console as follows
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 to the Server console as follows
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 attribute public static List OnlineUsers = new List () / / online user list / login connection / user Id / user name public void Register (string userName) {var connnectId = Context.ConnectionId; if (OnlineUsers.Count (x = > x.ConnectionId = = connnectId) = = 0) {if (x = > x.UserName = = userName) {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 users Clients.All.onConnected (connnectId, userName, OnlineUsers); send private chat / recipient users connect ID / content public void SendPrivateMessage (string toUserName, string message) {var fromConnectionId = 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;} / / represents all clients / Clients.AllExcept (params string [] excludeConnectionIds) / / except for all clients in the parameters / / Clients.Client (string connectionId); / / specific clients, this method is the key to our end-to-end chat / / Clients.Clients (IList connectionIds); / / clients in parameters / / Clients.Group (string groupName, params string [] excludeConnectionIds) / / specify client group, which is also the key to group chat / / Clients.Groups (IList groupNames, params string [] excludeConnectionIds); client group / / Clients.User (string userId) in parameters; / / specific user / / Clients.Users (IList userIds); / / user Console.WriteLine in parameters ("ConnectionId: {0}, InvokeMethod: {1}", Context.ConnectionId, "Send") Clients.All.addMessage (name, message); call / public override Task OnConnected () {Console.WriteLine ("client connection, connection ID is: {0}, current online population is {1}", Context.ConnectionId, OnlineUsers.Count+1); return base.OnConnected () Call / public override Task OnDisconnected (bool stopCalled) {var user = OnlineUsers.FirstOrDefault (u = > u.ConnectionId = = Context.ConnectionId) when disconnected; / / determine whether 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 (user); Console.WriteLine ("client disconnected, connection ID is: {0}, current online population is {1}", Context.ConnectionId, OnlineUsers.Count); return base.OnDisconnected (stopCalled);} public override Task OnReconnected () {return base.OnReconnected ();}
7. Add the Startup class to the Server console 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 and add the Program class to the Server console, as follows
Using Microsoft.Owin.Hosting;using System;namespace Server {class Program {static void Main (string [] args) {string url = "http://localhost:10086";// sets SignalR Hub Server external interface using (WebApp.Start (url)) / / launches SignalR Hub Server {Console.WriteLine (" Server running on {0} ", url); Console.ReadLine ();}
9. F5 is running
Then access http://localhost:10086/signalr/hubs in the browser
The results are as follows:
Thank you for reading this article carefully. I hope the article "sample Analysis of SignalR Self Host+MVC and other multi-end message push services" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.