我想使用SignalR保存数据。例如,
public void ReservationOpened(long contractId, string username)
{
// Save the contractId somewhere, that we can access it later. Let's call it ListOfOpenedIds
Clients.All.reservationOpened(contractId, username);
}
public void ReservationClosed(long contractId)
{
// look in ListOfOpenIds for contractId, and then remove it.
Clients.All.reservationClosed(contractId);
}
我怎样才能做到这一点?我听说不推荐使用SessionR。所以我想我不会使用Http.Current.Context.Session。
至于数据库方法,我不喜欢每次打开/关闭时使用dbWrite / dbRead的事实。
有人可以告诉我如何做到这一点吗?如果数据库方法是最好的方法,我应该在哪里初始化数据库连接?
答案 0 :(得分:0)
您可以将此数据存储在静态变量中。它将具有全局范围,并非每个用户都是唯一的,但如果您使用字典,则可以根据连接ID查找用户(会话)数据。
我使用会话管理器单例类,其中两个字典将连接ID映射到会话数据,将用户名映射到会话数据。这允许我通过连接ID识别连接用户,并在向特定用户发送消息时查找相关的连接ID。
“会话数据”类:
public class Player
{
public Player()
{
ConnectionIDs = new List<string>();
}
public List<string> ConnectionIDs { get; set; }
public string Name { get; set; }
public string username { get; set; }
}
“会话管理员”课程:
public class Lobby
{
private Lobby()
{
playersByUsername = new Dictionary<string, Player>();
playersByConnectionID = new Dictionary<string, Player>();
}
private static Lobby singleton;
public static Lobby Get()
{
if (singleton == null)
singleton = new Lobby();
return singleton;
}
Dictionary<string, Player> playersByUsername;
Dictionary<string, Player> playersByConnectionID;
public Player GetPlayerByUsername(string username)
{
if (playersByUsername.ContainsKey(username))
return playersByUsername[username];
return null;
}
public Player GetPlayerByConnectionID(string connectionID)
{
if (playersByConnectionID.ContainsKey(connectionID))
return playersByConnectionID[connectionID];
return null;
}
public void NewPlayer(Player player)
{
playersByUsername.Add(player.username, player);
foreach (string connectionID in player.ConnectionIDs)
playersByConnectionID.Add(connectionID, player);
}
public void NewConnection(string username, string connectionID)
{
playersByConnectionID.Add(connectionID, playersByUsername[username]);
playersByUsername[username].ConnectionIDs.Add(connectionID);
}
}