Abp集成SignalR
1.nuget安装 Abp.Web.SignalR 此nuget包依赖 Microsoft.Owin
以及Microsoft.Owin.Host.SystemWeb
2. WebModule 配置依赖 AbpWebSignalRModule
若是依赖带有起始业务的,还需引用 Ez.Application.Msg(本人自定义的消息业务处理模块) 和 Ez.Msg.Hub (本人自定义的消息HUB模块)两个项目
依赖 EzApplicationMsgModule 以及 EzMsgHubModule 此处可忽略
3.实现 IUserIdProvider 接口
public class SignalRUserFactory : IUserIdProvider
{
public string GetUserId(IRequest request)
{
if (request.Cookies.ContainsKey("SignalRId") && request.Cookies["SignalRId"] != null)
{
return request.Cookies["SignalRId"].Value;
}
return "";
}
}
4.添加 OwinStartup 类,并调阅 app.MapSignalR();启动signalr
app.UseCors(CorsOptions.AllowAll) 设置允许跨域访问,兼容ngix部署
[assembly: OwinStartup(typeof(Startup))]
namespace Ez.Web.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}
要使Startup 能够被调用进入必须nuget安装 Microsoft.Owin.Host.SystemWeb 引用
5.自定义HUB,形如下方
public class EzChatHubBase : AbpCommonHub, ITransientDependency
{
protected IOnlineClientManager OnlineClientManager { get; }
protected IOnlineClientInfoProvider ClientInfoProvider { get; }
public IMsgAppService _MsgManageAppService { get; }
private readonly ILogger _logger;
public EzChatHubBase(IOnlineClientManager onlineClientManager, IOnlineClientInfoProvider clientInfoProvider,
IMsgAppService msgManageAppService, ILogger logger, IUnitOfWorkManager unitOfWorkManager)
: base(onlineClientManager, clientInfoProvider)
{
OnlineClientManager = onlineClientManager;
ClientInfoProvider = clientInfoProvider;
_MsgManageAppService = msgManageAppService;
_logger = logger;
_unitOfWorkManager = unitOfWorkManager;
}
/// <summary>
/// 注册用户登录信息
/// </summary>
/// <param name="userInfo"></param>
public virtual void Regist(MsgUser userInfo)
{
var onlineClient = new OnlineClient(userInfo.ConnectionId, userInfo.IpAddress, userInfo.TenantId, userInfo.UserId);
onlineClient.Properties = userInfo.Properties;
onlineClient.Properties.Add("UserName", userInfo.UserName);
this.OnlineClientManager.Add(onlineClient);
_MsgManageAppService.AddLoginInfo(userInfo);
//Clients.Client(onlineClient.ConnectionId).getMessage(string.Format("User {0}: {1}", AbpSession.UserId, "登录"+DateTime.Now.ToString()));
Clients.All.userLogin(userInfo);
foreach (var client in this.OnlineClientManager.GetAllClients())
{
if (client.ConnectionId != userInfo.ConnectionId && client.UserId.HasValue)
{
var user = new MsgUser();
user.UserId = client.UserId.Value;
user.UserName = client.Properties["UserName"].ToString();
Clients.Client(onlineClient.ConnectionId).userLogin(user);
}
}
QueryUnreadMsgs(userInfo, onlineClient);
}
/// <summary>
/// 查询未读信息
/// </summary>
/// <param name="userInfo"></param>
/// <param name="onlineClient"></param>
public void QueryUnreadMsgs(MsgUser userInfo, OnlineClient onlineClient)
{
var unreadMsgList = _MsgManageAppService.QueryUnReciveAndUnreadMsgs(userInfo);
if (unreadMsgList != null)
{
for (int i = 0; i < unreadMsgList.Count; i++)
{
var msg = unreadMsgList[i];
Clients.Client(onlineClient.ConnectionId).receiveMessage(msg);
}
}
}
/// <summary>
/// 发送信息给用户
/// </summary>
/// <param name="msg">消息传输对象</param>
/// <returns>返回结果</returns>
public bool SendMessageToUser(MsgSendDto msg)
{
long srcUserId = 0;
try
{
//单独事务,不然会出现客户端收到消息更新消息状态不成功的情况
if (msg.IsSaveToDB)
{
using (var unitOfWork = _unitOfWorkManager.Begin())
{
var r = _MsgManageAppService.SendMsg(msg);
unitOfWork.Complete();
}
}
}
catch (Exception ex)
{
_logger.Error("保存消息失败", ex);
}
try
{
srcUserId = msg.SenderId;
EzChatHubHelper.Instance.SendMessage(OnlineClientManager, srcUserId, msg);
for (int i = 0; i < msg.MsgReceives.Count; i++)
{
var receive = msg.MsgReceives[i];
EzChatHubHelper.Instance.SendMessage(OnlineClientManager, receive.ReceiveId, msg);
}
}
catch (Exception ex)
{
_logger.Error("服务端发送消息失败", ex);
return false;
}
return true;
}
/// <summary>
/// 读取消息
/// </summary>
/// <param name="msg"></param>
public void ReadMsg(MsgReceiveDto msg)
{
var r = _MsgManageAppService.UpdateReadFlag(msg);
}
public void SendMessage(string message)
{
Clients.All.getMessage(string.Format("User {0}: {1}", AbpSession.UserId, message));
}
public async override Task OnConnected()
{
await base.OnConnected();
Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId);
}
public async override Task OnDisconnected(bool stopCalled)
{
var onlineClient = OnlineClientManager.Remove(Context.ConnectionId);
await base.OnDisconnected(stopCalled);
Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId);
}
/// <summary>
/// 获取连接ID,你可以写成自己的扩展方法,或设置成属性,自行定义
/// </summary>
/// <returns></returns>
public string GetSignalrID()
{
var connectionId = Context.ConnectionId;
if (Context.Request.Cookies["SignalRId"] != null)
{
return Context.Request.Cookies["SignalRId"].Value;
}
return "";
}
//public bool SendQcResult(List<RqResultDto> list)
//{
// var first = list.FirstOrDefault();
// var userId = Convert.ToInt64(first.OperatorId);
// var srcClients = OnlineClientManager.GetAllClients().Where(x => x.UserId == userId);
// if (srcClients != null)
// {
// foreach (var srcClient in srcClients)
// {
// Clients.Client(srcClient.ConnectionId).receiveQcResults(list);
// }
// }
// return true;
//}
private readonly IUnitOfWorkManager _unitOfWorkManager;
}
ok!!!
若有用就集个赞呗(:>)

浙公网安备 33010602011771号