You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

65 line
2.0 KiB

  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using DotNetty.Transport.Channels;
  7. using JT1078.DotNetty.Core.Metadata;
  8. namespace JT1078.DotNetty.Core.Session
  9. {
  10. /// <summary>
  11. /// JT1078 WebSocket会话管理
  12. /// </summary>
  13. public class JT1078WebSocketSessionManager
  14. {
  15. private readonly ILogger<JT1078WebSocketSessionManager> logger;
  16. public JT1078WebSocketSessionManager(
  17. ILoggerFactory loggerFactory)
  18. {
  19. logger = loggerFactory.CreateLogger<JT1078WebSocketSessionManager>();
  20. }
  21. private ConcurrentDictionary<string, JT1078WebSocketSession> SessionDict = new ConcurrentDictionary<string,JT1078WebSocketSession>();
  22. public int SessionCount
  23. {
  24. get
  25. {
  26. return SessionDict.Count;
  27. }
  28. }
  29. public List<JT1078WebSocketSession> GetSessions(string userId)
  30. {
  31. return SessionDict.Where(m => m.Value.UserId == userId).Select(m=>m.Value).ToList();
  32. }
  33. public void TryAdd(string userId,IChannel channel)
  34. {
  35. SessionDict.TryAdd(channel.Id.AsShortText(), new JT1078WebSocketSession(channel, userId));
  36. if (logger.IsEnabled(LogLevel.Information))
  37. {
  38. logger.LogInformation($">>>{userId},{channel.Id.AsShortText()} Channel Connection.");
  39. }
  40. }
  41. public void RemoveSessionByChannel(IChannel channel)
  42. {
  43. if (channel.Open&& SessionDict.TryRemove(channel.Id.AsShortText(), out var session))
  44. {
  45. if (logger.IsEnabled(LogLevel.Information))
  46. {
  47. logger.LogInformation($">>>{session.UserId},{session.Channel.Id.AsShortText()} Channel Remove.");
  48. }
  49. }
  50. }
  51. public IEnumerable<JT1078WebSocketSession> GetAll()
  52. {
  53. return SessionDict.Select(s => s.Value).ToList();
  54. }
  55. }
  56. }