这是前端代码:
var chat = $.connection.chatHub;
$.connection.hub.start().done(function () {
chat.server.start();
});
chat.client.addNewMessageToPage = function (username) {
alertify.success(name + message);
};
$.connection.hub.disconnected(function () {
setTimeout(function () { $.connection.hub.start(); }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
首次加载页面时,此方法有效,但是刷新页面时,计时器和警报提示似乎运行两次。
这是后端代码:
namespace DHPGROUP
{
public class ChatHub : Hub
{
private Timer timer = new Timer();
private static readonly ConcurrentDictionary<string, UserHubModels> Users = new ConcurrentDictionary<string, UserHubModels>(StringComparer.InvariantCultureIgnoreCase);
private void start()
{
timer.Interval = 15000;
timer.Elapsed += Tim_Elapsed2;
timer.Start();
}
private void Tim_Elapsed2(object sender, ElapsedEventArgs e)
{
PublicChatHub pubChatHub = new PublicChatHub();
Clients.All.addNewMessageToPage(pubChatHub.GetCalls());
}
public override Task OnConnected()
{
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
var user = Users.GetOrAdd(userName, _ => new UserHubModels
{
UserName = userName,
ConnectionIds = new HashSet<string>()
});
lock (user.ConnectionIds)
{
user.ConnectionIds.Add(connectionId);
if (user.ConnectionIds.Count == 1)
{
Clients.Others.userConnected(userName);
start();
}
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
UserHubModels user;
Users.TryGetValue(userName, out user);
if (user != null)
{
lock (user.ConnectionIds)
{
user.ConnectionIds.RemoveWhere(cid => cid.Equals(connectionId));
if (!user.ConnectionIds.Any())
{
UserHubModels removedUser;
Users.TryRemove(userName, out removedUser);
Clients.Others.userDisconnected(userName);
timer.Enabled = false;
timer.Stop();
timer.Dispose();
}
}
}
return base.OnDisconnected(stopCalled);
}
}
public class UserHubModels
{
public string UserName { get; set; }
public HashSet<string> ConnectionIds { get; set; }
}
public class PublicChatHub
{
private readonly IUnitOfWork _unitOfWork = new UnitOfWork(new ApplicationDbContext());
public List<CallViewModel> GetCalls()
{
try
{
var currentDateTime = DateTime.Now;
var queryCallViewModel = _unitOfWork.CallRepository.AsQueryable()
.Where(tr => !tr.Accomplished)
.Where(rt => rt.DateTimeStartUtc >= currentDateTime && rt.DateTimeEndUtc <= currentDateTime)
.Select(er => new CallViewModel
{
Id = er.Id,
Caption = er.Caption,
}).ToList();
return queryCallViewModel;
}
catch (Exception)
{
throw;
}
}
}
}