WsSession.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 CancellationToken DisconnetCancellationToken => disconnectCancellationTokenSource.Token;
  31. //public event OCPPClientDataEventHandler<WsSession, String> m_ReceiveData;
  32. public event EventHandler<string> SessionClosed;
  33. private CancellationTokenSource disconnectCancellationTokenSource = new CancellationTokenSource();
  34. private Task ReceiveLoopTask;
  35. private readonly ILogger<WsSession> logger;
  36. private void Init(WebSocket webSocket)
  37. {
  38. _WebSocket = webSocket;
  39. LastActiveTime = DateTime.UtcNow;
  40. ReceiveLoopTask = StartReceivd(webSocket, disconnectCancellationTokenSource.Token);
  41. }
  42. private async Task StartReceivd(WebSocket webSocket, CancellationToken token)
  43. {
  44. logger.LogInformation("{id} {func} {Path} Start", SessionID, nameof(StartReceivd), Path);
  45. byte[] prevBuffer = new byte[0];
  46. byte[] receivdBuffer = new byte[0];
  47. int bufferExpand = 1;
  48. int receivedBytes = 0;
  49. while (!token.IsCancellationRequested)
  50. {
  51. var tempReceiveBuffer = new byte[1024 * 4];
  52. WebSocketReceiveResult result = null;
  53. try
  54. {
  55. result = await webSocket.ReceiveAsync(new ArraySegment<byte>(tempReceiveBuffer), token);
  56. }
  57. catch (Exception e)
  58. {
  59. _ = BruteClose(e.Message);
  60. break;
  61. }
  62. LastActiveTime = DateTime.UtcNow;
  63. if (result == null || result.CloseStatus.HasValue)
  64. {
  65. //closed gracefully
  66. await GracefulClose(result.CloseStatus.Value);
  67. break;
  68. }
  69. prevBuffer = receivdBuffer;
  70. receivdBuffer = new byte[1024 * 4 * bufferExpand];
  71. Array.Copy(prevBuffer, 0, receivdBuffer, 0, receivedBytes);
  72. Array.Copy(tempReceiveBuffer, 0, receivdBuffer, receivedBytes, result.Count);
  73. receivedBytes += result.Count;
  74. if (!result.EndOfMessage)
  75. {
  76. bufferExpand++;
  77. continue;
  78. }
  79. var received = Encoding.UTF8.GetString(receivdBuffer, 0, receivedBytes);
  80. //logger.LogInformation("{func}:{Path} {value}", nameof(StartReceivd), Path, received);
  81. HandleReceivedData(received);
  82. bufferExpand = 1;
  83. receivedBytes = 0;
  84. }
  85. }
  86. internal virtual void HandleReceivedData(string data)
  87. {
  88. }
  89. internal Task Send(string dataString)
  90. {
  91. //logger.LogInformation("{func}:{Path} {value}", nameof(Send), Path, dataString);
  92. var data = Encoding.UTF8.GetBytes(dataString);
  93. return Send(data);
  94. }
  95. internal Task Close()
  96. {
  97. return ServerClose();
  98. }
  99. private async Task Send(byte[] data)
  100. {
  101. try
  102. {
  103. await ClientWebSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: disconnectCancellationTokenSource.Token);
  104. }
  105. catch (Exception e)
  106. {
  107. logger.LogInformation("{func} {Path} exception:{msg}", nameof(Send), Path, e.Message);
  108. }
  109. }
  110. private Task ServerClose()
  111. {
  112. //logger.LogInformation("{func}:{Path}", nameof(ServerClose), Path);
  113. SessionClosed?.Invoke(this, "ServerShutdown");
  114. return InternalClose(WebSocketCloseStatus.NormalClosure, "ServerShutdown");
  115. }
  116. private Task GracefulClose(WebSocketCloseStatus closeStatus)
  117. {
  118. //logger.LogInformation("{func}:{Path} {value}", nameof(GracefulClose), Path, closeStatus);
  119. SessionClosed?.Invoke(this, closeStatus.ToString());
  120. return InternalClose(closeStatus, null);
  121. }
  122. private Task BruteClose(string description)
  123. {
  124. //logger.LogInformation("{func}:{Path} {value}", nameof(ServerClose), Path, description);
  125. SessionClosed?.Invoke(this, description);
  126. return InternalClose(WebSocketCloseStatus.EndpointUnavailable, description);
  127. }
  128. private async Task InternalClose(WebSocketCloseStatus closeStatus, string description)
  129. {
  130. try
  131. {
  132. await _WebSocket.CloseAsync(closeStatus, description, default);
  133. }
  134. catch
  135. {
  136. }
  137. finally
  138. {
  139. _WebSocket.Dispose();
  140. }
  141. disconnectCancellationTokenSource.Cancel();
  142. EndConnSemaphore.Release();
  143. }
  144. }