我正在使用SignalR库来显示在线用户。目前我能够显示在线用户的总数,但是当我用他们的名字显示在线用户列表时,这让我很困惑。 我不知道如何管理目前的特定在线状态我想通过数据库管理特定的在线用户状态。我有一个表,我想在Onconnected和OnDisconnected方法上管理。 请告诉我如何显示在线用户列表 这是我的代码。
<script src="~/Content/Scripts/jquery-ui.min.js"></script>
<script src="~/Content/Scripts/jquery.ui.touch-punch.js"></script>
<script src="~/Content/Scripts/jquery.signalR-1.1.3.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script>
$(document).ready(function () {
$(function () {
// Reference the auto-generated proxy for the hub.
var userActivity = $.connection.userActivityHub;
var Chat = $.connection.Chat;
// Create a function that the hub can call back to display messages.
userActivity.client.updateUsersOnlineCount = function (count) {
// Add the message to the page.
console.log('Count :' + count);
$('#usersCount').text(count);
};
//Chat.server.SetName($.connection.hub.id, $("#displayname").val())
$.connection.hub.start();
});
});
</script>
I have a HubClass named UserActivityHub.
using System.Collections.Generic;
using System;
using System.Web;
using IMWedding.BAL.UserInfos;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace IMWedding.Utils
{
[HubName("userActivityHub")]
public class UserActivityHub : Hub
{
IUserInfosRepository _userRepo;
public UserActivityHub()
{
this._userRepo = new UserInfosRepository();
}
/// <summary>
/// The count of users connected.
/// </summary>
public static List<string> Users = new List<string>();
/// <summary>
/// Sends the update user count to the listening view.
/// </summary>
/// <param name="count">
/// The count.
/// </param>
public void Send(int count)
{
// Call the addNewMessageToPage method to update clients.
var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
context.Clients.All.updateUsersOnlineCount(count);
}
/// <summary>
/// The OnConnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
///
public override System.Threading.Tasks.Task OnConnected()
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
//if (!string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["UserInfoID"])))
//{
// var detail = _userRepo.GetUserDetailByUserID(UserId);
// if (detail != null)
// {
// if (!string.IsNullOrEmpty(clientId))
// {
// detail.CreatedBy = UserId;
// bool Result = _userRepo.AddUserDetail(detail);
// }
// }
//}
// Send the current count of users
Send(Users.Count);
return base.OnConnected();
}
public void SetName(string cid, string name)
{
//Users.Find(uo => uo.con_id == cid).client_name = name;
}
/// <summary>
/// The OnReconnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
//public override System.Threading.Tasks.Task OnReconnected()
//{
// string clientId = GetClientId();
// if (Users.IndexOf(clientId) == -1)
// {
// Users.Add(clientId);
// }
// // Send the current count of users
// Send(Users.Count);
// return base.OnReconnected();
//}
/// <summary>
/// The OnDisconnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public override System.Threading.Tasks.Task OnDisconnected(bool StopCalled)
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) > -1)
{
Users.Remove(clientId);
}
if (!string.IsNullOrEmpty(clientId))
{
bool Result = _userRepo.RemoveDetail(clientId);
}
// Send the current count of users
Send(Users.Count);
return base.OnDisconnected(StopCalled);
}
/// <summary>
/// Get's the currently connected Id of the client.
/// This is unique for each client and is used to identify
/// a connection.
/// </summary>
/// <returns>The client Id.</returns>
private string GetClientId()
{
string clientId = "";
if (Context.QueryString["clientId"] != null)
{
// clientId passed from application
clientId = this.Context.QueryString["clientId"];
}
if (string.IsNullOrEmpty(clientId.Trim()))
{
clientId = Context.ConnectionId;
}
return clientId;
}
}
}
The application_start method in global.asax File
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
MailSchedulerModel objmodel = new MailSchedulerModel();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
// GlobalFilters.Filters.Add(new )
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Here it is my Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.MapSignalR();
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
&#13;
答案 0 :(得分:1)
首先,在SendUserList
中心内创建UserActivityHub
方法。
public void SendUserList(List<string> users)
{
var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
context.Clients.All.updateUserList(users);
}
然后,在System.Threading.Tasks.Task OnConnected()
方法调用SendUserList
方法内;
public override System.Threading.Tasks.Task OnConnected()
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
//if (!string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["UserInfoID"])))
//{
// var detail = _userRepo.GetUserDetailByUserID(UserId);
// if (detail != null)
// {
// if (!string.IsNullOrEmpty(clientId))
// {
// detail.CreatedBy = UserId;
// bool Result = _userRepo.AddUserDetail(detail);
// }
// }
//}
// Send the current users
SendUserList(Users);
return base.OnConnected();
}
最后,在javascript部分插入updateUserList
函数来处理从服务器推送的userList
;
$(document).ready(function () {
$(function () {
// Reference the auto-generated proxy for the hub.
var userActivity = $.connection.userActivityHub;
var Chat = $.connection.Chat;
// Create a function that the hub can call back to display messages.
userActivity.client.updateUsersOnlineCount = function (count) {
// Add the message to the page.
console.log('Count :' + count);
$('#usersCount').text(count);
};
userActivity.client.updateUserList = function (userList) {
//Take action with userList
};
//Chat.server.SetName($.connection.hub.id, $("#displayname").val())
$.connection.hub.start();
});
});