WsSession.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Logging;
  3. using System.Net;
  4. using System.Net.WebSockets;
  5. using System.Text;
  6. namespace EVCB_OCPP.WSServer.Service.WsService;
  7. public class WsSession
  8. {
  9. public WsSession(ILogger<WsSession> logger)
  10. {
  11. this.logger = logger;
  12. }
  13. public PathString? Path { get; set; }
  14. public string UriScheme { get; set; }
  15. public string SessionID { get; set; }
  16. public IPEndPoint Endpoint { get; internal set; }
  17. public DateTime LastActiveTime { get; set; }
  18. private WebSocket _WebSocket;
  19. public WebSocket ClientWebSocket
  20. {
  21. get => _WebSocket;
  22. set
  23. {
  24. Init(value);
  25. }
  26. }
  27. public WebSocketState State => ClientWebSocket.State;
  28. public string SecWebSocketProtocol => ClientWebSocket.SubProtocol;
  29. public SemaphoreSlim EndConnSemaphore { get; } = new SemaphoreSlim(0);
  30. //public event OCPPClientDataEventHandler<WsSession, String> m_ReceiveData;
  31. public event EventHandler<string> SessionClosed;
  32. private CancellationTokenSource disconnectCancellationTokenSource = new CancellationTokenSource();
  33. private Task ReceiveLoopTask;
  34. private readonly ILogger<WsSession> logger;
  35. private void Init(WebSocket webSocket)
  36. {
  37. _WebSocket = webSocket;
  38. LastActiveTime = DateTime.UtcNow;
  39. ReceiveLoopTask = StartReceivd(webSocket, disconnectCancellationTokenSource.Token);
  40. }
  41. private async Task StartReceivd(WebSocket webSocket, CancellationToken token)
  42. {
  43. logger.LogInformation("{id} {func} {Path} Start", SessionID, nameof(StartReceivd), Path);
  44. byte[] receivdBuffer = new byte[0];
  45. int bufferExpand = 1;
  46. int receivedBytes = 0;
  47. while (!token.IsCancellationRequested)
  48. {
  49. var tempReceiveBuffer = new byte[1024 * 4];
  50. WebSocketReceiveResult result = null;
  51. try
  52. {
  53. result = await webSocket.ReceiveAsync(new ArraySegment<byte>(tempReceiveBuffer), token);
  54. }
  55. catch (Exception e)
  56. {
  57. _ = BruteClose(e.Message);
  58. break;
  59. }
  60. LastActiveTime = DateTime.UtcNow;
  61. if (result == null || result.CloseStatus.HasValue)
  62. {
  63. //closed gracefully
  64. await GracefulClose(result.CloseStatus.Value);
  65. break;
  66. }
  67. receivdBuffer = new byte[1024 * 4 * bufferExpand];
  68. Array.Copy(tempReceiveBuffer, 0, receivdBuffer, receivedBytes, result.Count);
  69. receivedBytes += result.Count;
  70. if (!result.EndOfMessage)
  71. {
  72. bufferExpand++;
  73. continue;
  74. }
  75. var received = Encoding.UTF8.GetString(receivdBuffer, 0, receivedBytes);
  76. //logger.LogInformation("{func}:{Path} {value}", nameof(StartReceivd), Path, received);
  77. HandleReceivedData(received);
  78. bufferExpand = 1;
  79. receivedBytes = 0;
  80. }
  81. }
  82. internal virtual void HandleReceivedData(string data)
  83. {
  84. }
  85. internal Task Send(string dataString)
  86. {
  87. //logger.LogInformation("{func}:{Path} {value}", nameof(Send), Path, dataString);
  88. var data = Encoding.UTF8.GetBytes(dataString);
  89. return Send(data);
  90. }
  91. internal Task Close()
  92. {
  93. return ServerClose();
  94. }
  95. private async Task Send(byte[] data)
  96. {
  97. try
  98. {
  99. await ClientWebSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: disconnectCancellationTokenSource.Token);
  100. }
  101. catch (Exception e)
  102. {
  103. logger.LogInformation("{func} {Path} exception:{msg}", nameof(Send), Path, e.Message);
  104. }
  105. }
  106. private Task ServerClose()
  107. {
  108. logger.LogInformation("{func}:{Path}", nameof(ServerClose), Path);
  109. SessionClosed?.Invoke(this, "ServerShutdown");
  110. return InternalClose(WebSocketCloseStatus.NormalClosure, "ServerShutdown");
  111. }
  112. private Task GracefulClose(WebSocketCloseStatus closeStatus)
  113. {
  114. logger.LogInformation("{func}:{Path} {value}", nameof(GracefulClose), Path, closeStatus);
  115. SessionClosed?.Invoke(this, closeStatus.ToString());
  116. return InternalClose(closeStatus , null);
  117. }
  118. private Task BruteClose(string description)
  119. {
  120. logger.LogInformation("{func}:{Path} {value}", nameof(ServerClose), Path, description);
  121. SessionClosed?.Invoke(this, description);
  122. return InternalClose(WebSocketCloseStatus.EndpointUnavailable, description);
  123. }
  124. private async Task InternalClose(WebSocketCloseStatus closeStatus, string description)
  125. {
  126. try
  127. {
  128. await _WebSocket.CloseAsync(closeStatus, description, default);
  129. }
  130. catch
  131. {
  132. }
  133. finally
  134. {
  135. _WebSocket.Dispose();
  136. }
  137. disconnectCancellationTokenSource.Cancel();
  138. EndConnSemaphore.Release();
  139. }
  140. }