


This article mainly introduces multi-terminal message push services such as SignalR Self Host+MVC in detail. It has certain reference value. Interested friends can refer to it
1. Overview
Due to project needs, there is a module function in the company's project recently, which needs to be used to obtain immediate approval notification; the original design plan was to use ajax to poll the server regularlyQuery , it was fine when the amount of data and usage was not large at the beginning. Later, as the usage increased and the complexity of various businesses in the system increased, the pressure on the server also increased, so I wanted to replace it with message push. Ajax polling query, when there is an approval submission, the push method is called to push the message to the next approver, thus reducing the pressure on the server.
Signal is an html websocket framework supported by Microsoft that runs on the .NET platform. The main purpose of its appearance is to enable the server to actively push messages to the client page, so that the client does not have to resend the request or use polling technology to obtain the message. And the compatibility of SignalR is also very powerful, so I won’t go into details here. Now that you have chosen SignalR, let’s get started!
My idea is to make SignalR a self-hosted service and separate it from our b/s project. The advantages are: 1. The push service does not depend on iis. Even if iis fails, we The 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;
2. Create the server
Without further ado, this is my first time writing a blog. After introducing the business scenarios and ideas, let’s start coding.
1. Use VS to create a solution named "SignalRProject";
2. Create a new control named Server under the SignalRProject solution Taiwan
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, the code is 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 in the Server console, the code is 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 { // 静态属性 public static List<UserInfo> OnlineUsers = new List<UserInfo>(); // 在线用户列表 /// <summary> /// 登录连线 /// </summary> /// <param name="userId">用户Id</param> /// <param name="userName">用户名</param> public void Register(string userName) { var connnectId = Context.ConnectionId; if (OnlineUsers.Count(x => x.ConnectionId == connnectId) == 0) { if (OnlineUsers.Any(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); } //添加在线人员 OnlineUsers.Add(new UserInfo { ConnectionId = connnectId, UserName = userName, LastLoginTime = DateTime.Now }); } // 所有客户端同步在线用户 Clients.All.onConnected(connnectId, userName, OnlineUsers); } /// <summary> /// 发送私聊 /// </summary> /// <param name="toUserId">接收方用户连接ID</param> /// <param name="message">内容</param> 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 { //表示对方不在线 Clients.Caller.absentSubscriber(); } } public void Send(string name, string message) { //Clients.All { get; } // 代表所有客户端 //Clients.AllExcept(params string[] excludeConnectionIds); // 除了参数中的所有客户端 //Clients.Client(string connectionId); // 特定的客户端,这个方法也就是我们实现端对端聊天的关键 //Clients.Clients(IList<string> connectionIds); // 参数中的客户端 //Clients.Group(string groupName, params string[] excludeConnectionIds); // 指定客户端组,这个也是实现群聊的关键所在 //Clients.Groups(IList<string> groupNames, params string[] excludeConnectionIds);参数中的客户端组 //Clients.User(string userId); // 特定的用户 //Clients.Users(IList<string> userIds); // 参数中的用户 Console.WriteLine("ConnectionId:{0}, InvokeMethod:{1}", Context.ConnectionId, "Send"); Clients.All.addMessage(name, message); } /// <summary> /// 连线时调用 /// </summary> /// <returns></returns> public override Task OnConnected() { Console.WriteLine("客户端连接,连接ID是:{0},当前在线人数为{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.FirstOrDefault(u => u.ConnectionId == Context.ConnectionId); // 判断用户是否存在,存在则删除 if (user == null) { return base.OnDisconnected(stopCalled); } Clients.All.onUserDisconnected(user.ConnectionId, user.UserName); //调用客户端用户离线通知 // 删除用户 OnlineUsers.Remove(user); Console.WriteLine("客户端断线,连接ID是:{0},当前在线人数为{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) { //允许CORS跨域 app.UseCors(CorsOptions.AllowAll); app.MapSignalR(); } } }
8. Modify the Server Add the Program class to the console, the code is as follows
using Microsoft.Owin.Hosting; using System; namespace Server { class Program { static void Main(string[] args) { string url = "http://localhost:10086";//设定 SignalR Hub Server 对外的接口 using (WebApp.Start(url))//启动 SignalR Hub Server { Console.WriteLine("Server running on {0}", url); Console.ReadLine(); } } } }
9. Run F5
and then access http in the browser ://localhost:10086/signalr/hubs
The results are as follows:
As you can see in the picture above, the content is basically completed. Let’s talk about it first today. We don’t have time. It's early, let's take a rest first, and I will make up for the next article when I have time.
The above is the detailed content of SignalR Self Host multi-terminal message push service example (3). For more information, please follow other related articles on the PHP Chinese website!

近期不少的win11用户们反映关机的时候提示taskhostwindow任务宿主正在执行关闭任务,那么这是怎么回事?用户们可以进入到本地注册表编辑器下的Desktop文件夹,然后在右边的窗口中选择AutoEndTasks来进行设置就可以了。下面就让本站来为用户们来仔细的介绍一下关机出现这个问题的解决方法吧。windows11关机提示taskhostwindow任务宿主正在执行关闭任务的解决方法1、使用组合键win键+r键,输入“regedit”,回车,如下图所示。2、寻找[HKEY

当我们启动任务管理器以终止任务或停止应用程序时,我们通常会发现大量进程正在运行。这是完全正常的。但是,有时我们会看到一些程序正在使用我们完全不知道的系统资源。其中一个进程是聚合器 host.exe,它最近在用户中引起了一些混乱。其中一些进程可能是合法的 Windows 要求,但其他进程可能是在后台运行并在用户不知情或未经用户同意的情况下导致问题的恶意程序。在我们看到您可以在 Windows 11 中启动任务管理器的五种方式之后,我们将向您展示如何检查聚合器 host.exe 是安全还是病毒。跟上

“no route to host”的解决办法有检查网络连接、检查IP地址和端口、检查防火墙配置、检查路由配置、检查网络设备配置、检查网络服务状态、检查网络配置和联系网络管理员等。详细介绍:1、检查网络连接,确保客户端和目标主机之间的网络连接正常,可以尝试通过ping命令或其他网络工具测试网络连通性,检查网线、无线网络、路由器等硬件设备是否正常工作,确保网络连接稳定等等。

master和host的区别有:1、host可以扮演客户端或服务器的角色,而master是分布式系统中负责协调和管理其他从服务器的中央服务器;2、host是普通的计算机设备,而master通常具有更高的处理能力和资源,用于处理和分发任务、管理数据和维护整个系统的稳定性;3、host是网络中的一个节点,而master是在分布式系统中担任核心角色的服务器。

报错的原因NameResolutionError(self.host,self,e)frome是由urllib3库中的异常类型,这个错误的原因是DNS解析失败,也就是说,试图解析的主机名或IP地址无法找到。这可能是由于输入的URL地址不正确,或者DNS服务器暂时不可用导致的。如何解决解决此错误的方法可能有以下几种:检查输入的URL地址是否正确,确保它是可访问的确保DNS服务器可用,您可以尝试在命令行中使用"ping"命令来测试DNS服务器是否可用尝试使用IP地址而不是主机名来访问网站如果是在代理

WMIProviderHost进程在Windows11中起着至关重要的作用。它使其他应用程序可以请求有关您的计算机的信息。与WMIProviderHost相关的进程通常在后台运行;因此,它们通常不会消耗大量系统资源。但是,据报道,该服务有时会因为其他应用程序而使用超过50%的CPU功率。令人担忧的是,您的计算机处理器几乎以最大容量长时间运行,因为这可能导致过热和系统组件损坏。在今天的教程中,我们将研究为什么WMIProviderHost在Windows11上的C

host文件位于路径“C:\Windows\System32\drivers\etc”下;host文件是一个纯文本的文件,用普通的文本编辑软件,如记事本等都能打开;host文件的作用是包含IP地址和Host name主机名的映射关系。

在介绍Python的self用法之前,先来介绍下Python中的类和实例我们知道,面向对象最重要的概念就是类(class)和实例(instance),类是抽象的模板,比如学生这个抽象的事物,可以用一个Student类来表示。而实例是根据类创建出来的一个个具体的“对象”,每一个对象都从类中继承有相同的方法,但各自的数据可能不同。1、以Student类为例,在Python中,定义类如下:classStudent(object):pass(Object)表示该类从哪个类继承下来的,Object类是所有


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
