1.在UI层和组件层(Componets)中NuGet添加Signalr包
选择1.0.1版本的就行了。
2.在组件层(Componets)中添加一个NotificationHub.cs类
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace YouYi.Market.Componets
{
public class NotificationHub : Hub
{
///
/// 建立连接时触发
///
///
public override async Task OnConnectedAsync()
{
//给所有的客户端发送消息 方法名 自己的连接Id
await Clients.All.SendAsync("ShangXian", Context.ConnectionId);
}
///
/// 离开连接时触发
///
///
///
public override async Task OnDisconnectedAsync(Exception ex)
{
//给所有客户端发送消息 方法名 自己的连接Id
await Clients.All.SendAsync("XiaXian", Context.ConnectionId);
}
///
/// 向所有人推送消息
///
///
///
public Task Send(string message)
{
return Clients.All.SendAsync("ReceiveMessage", $"{message}");
}
///
/// 向指定组推送消息(群消息)
///
///
///
///
public Task SendToGroup(string groupName, string message)
{
// 指定一个组 消息
return Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId}@{groupName}: {message}");
}
///
/// 加入指定组并向组推送消息
///
///
///
public async Task JoinGroup(string groupName)
{
//添加群里去 当前用户添加到一个群里去
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
//给群里的人发送一个消息
await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} joined {groupName}");
}
///
/// 退出指定组并向组推送消息
///
///
///
public async Task LeaveGroup(string groupName)
{
//退出群
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
//发送退出群聊消息
await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} left {groupName}");
}
///
/// 向指定Id推送消息
///
/// 要推送消息的对象
///
///
public Task Echo(string userid, string message)
{
// Clients.User 用户ID
// 在线ID
return Clients.Client(userid).SendAsync("Shou", Context.ConnectionId, message);
}
}
}
3.在UI层的Startup.cs类中注入服务与中间件
中间件:
//注册Signalr中间件
app.UseSignalR(route=> {
//映射一个Hub
route.MapHub("/notifyHub");
});
服务:
//注册signalr服务
services.AddSignalR();
4.在登陆方法中
先注入NotificationHub接口
private IUserInfoService userInfoService;
private IHubContext hubContext;
public AccountController(IUserInfoService userInfoService, IHubContext hubContext)
{
this.hubContext = hubContext;
this.userInfoService = userInfoService;
}
1>广播消息
2>单点消息
3>轮播消息
public class AccountController : Controller
{
private IUserInfoService userInfoService;
private IHubContext hubContext;
public AccountController(IUserInfoService userInfoService, IHubContext hubContext)
{
this.hubContext = hubContext;
this.userInfoService = userInfoService;
}
///
/// 登陆页面
///
///
public IActionResult Login()
{
//判断是否存在cookie值
//用户的身份是否已经授权
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
return View();
}
///
/// 验证登陆
///
///
public async Task ValidateLoginAsync(UserInfo user)
{
var result = userInfoService.ValidateLogin(user.UserName, user.UserPwd);
//判断
if (result.success)
{
//获取当前用户信息
UserInfo userInfo = result.data;
//写入session
//set设置 get获取
HttpContext.Session.Set("UserInfo", userInfo);
//设置cookie
var identity = new ClaimsIdentity("Forms"); // 指定身份认证类型
identity.AddClaim(new Claim(ClaimTypes.Sid, userInfo.Id.ToString())); // 用户Id
identity.AddClaim(new Claim(ClaimTypes.Name, userInfo.UserName)); // 用户名称
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString())); // 用户身份
//好友上线
//数据库的第一个用户的Id
//await hubContext.Clients.User("13").SendAsync("ReceiveMessage", $"你的好友{userInfo.UserName}上线了");
//推送系统公告消息
//await hubContext.Clients.All.SendAsync("ReceiveMessage","今天放假");
//轮播信息
TimerSehd();
//创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
return Json(result);
}
///
/// 退出登陆
///
///
public async Task LoginOutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login", "Account");
}
public void TimerSehd()
{
Timer t = new Timer(SenMessageAsync, null, 0, 1000);
}
public void SenMessageAsync(object ojb)
{
string userId = Guid.NewGuid().ToString();
hubContext.Clients.All.SendAsync("ReceiveMessage", $"{userId}今天休息");
}
}
5.登陆页面中发送消息
1>引用js
2>jquery
6.Index页面
1>引用js
2>页面中设置一个div
3>jquery
7.注意事项
1>在中间件注册时的命名(/notifyHub)要和页面中的创建websocket的命名(/notifyHub)一致
中间件注册:
页面创建websocket:
2>登陆方法中的SendAsync()方法的第一个参数(ReceiveMessage)要和组件层(Componets)的 NotificationHub.cs中的命名一致(ReceiveMessage)
登陆方法:
NotificationHub.cs: