基于SignalR的消息推送与二维码扫描登录实现代码(2)

using System;using System.Collections.Concurrent;using System.Timers;namespace TxSms.SingalR{ public class SessionTimer : IDisposable { /// <summary> /// 存储客户端对应的Timer /// </summary> public static readonly ConcurrentDictionary<string, SessionTimer> Timers; private readonly Timer _timer; static SessionTimer() { Timers = new ConcurrentDictionary<string, SessionTimer>(); } /// <summary> /// 构造函数 /// </summary> /// <param></param> private SessionTimer(string connectionId) { ConnectionId = connectionId; _timer = new Timer { Interval = Utility.ActivityTimerInterval() }; _timer.Elapsed += (s, e) => MonitorElapsedTime(); _timer.Start(); } public int TimeCount { get; set; } /// <summary> /// 客户端连接Id /// </summary> public string ConnectionId { get; set; } /// <summary> /// 启动Timer /// </summary> /// <param> </param> public static void StartTimer(string connectionId) { var newTimer = new SessionTimer(connectionId); if (!Timers.TryAdd(connectionId, newTimer)) { newTimer.Dispose(); } } /// <summary> /// 停止Timer /// </summary> /// <param> </param> public static void StopTimer(string connectionId) { SessionTimer oldTimer; if (Timers.TryRemove(connectionId, out oldTimer)) { oldTimer.Dispose(); } } /// <summary> /// 重置Timer /// </summary> public void ResetTimer() { TimeCount = 0; _timer.Stop(); _timer.Start(); } public void Dispose() { // Stop might not be necessary since we call Dispose _timer.Stop(); _timer.Dispose(); } /// <summary> /// 给客户端发送消息 /// </summary> private void MonitorElapsedTime() { Utility.ClearExpiredUUID(); var uuid = Utility.GetUUID(ConnectionId); //if (TimeCount >= Utility.TimerValue()) //{ // StopTimer(ConnectionId); // Notifier.SendQRCodeUUID(ConnectionId, uuid); // Notifier.SessionTimeOut(ConnectionId, TimeCount); //} //else // { Notifier.SendQRCodeUUID(ConnectionId, uuid); Notifier.SendElapsedTime(ConnectionId, TimeCount); //} TimeCount++; if (TimeCount > 1000) { TimeCount = 0; } } }}

3.2.4 Utility.cs 基础配置

满足时钟、获取QRCode等

using TxSms.Actions;namespace TxSms.SingalR { internal class Utility { public static int IntNum = 0; /// <summary> /// 时间间隔 /// </summary> /// <returns></returns> public static int TimerValue() { return 1000; } public static double ActivityTimerInterval() { return 1000.0; } /// <summary> /// 获取当前UUID /// </summary> /// <returns></returns> public static string GetUUID(string connectionId) { try { var model = new QRCodeAction().GetValidModel(connectionId); return model.ToJson(connectionId); } catch { return "ERROR"; } } /// <summary> /// 删除过期UUID /// </summary> public static void ClearExpiredUUID() { IntNum++; if (IntNum <= 1000) return; new QRCodeAction().ClearExpiredUUID(); IntNum = 0; } }}

3.2.5 SignalR在MVC中启动配置

在MVC中,启动项目进行如下配置:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdpsyw.html