SharpWebSocket.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Emby.Server.Implementations.Net;
  7. using Microsoft.Extensions.Logging;
  8. namespace Emby.Server.Implementations.SocketSharp
  9. {
  10. public class SharpWebSocket : IWebSocket
  11. {
  12. /// <summary>
  13. /// The logger
  14. /// </summary>
  15. private readonly ILogger _logger;
  16. public event EventHandler<EventArgs> Closed;
  17. /// <summary>
  18. /// Gets or sets the web socket.
  19. /// </summary>
  20. /// <value>The web socket.</value>
  21. private WebSocket WebSocket { get; set; }
  22. private TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  23. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  24. private bool _disposed = false;
  25. public SharpWebSocket(WebSocket socket, ILogger logger)
  26. {
  27. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  28. WebSocket = socket ?? throw new ArgumentNullException(nameof(socket));
  29. }
  30. public Task StartReceive()
  31. {
  32. return _taskCompletionSource.Task;
  33. }
  34. private void OnSocketError(object sender, SocketHttpListener.ErrorEventArgs e)
  35. {
  36. _logger.LogError("Error in SharpWebSocket: {Message}", e.Message ?? string.Empty);
  37. // Closed?.Invoke(this, EventArgs.Empty);
  38. }
  39. private void OnSocketClose(object sender, SocketHttpListener.CloseEventArgs e)
  40. {
  41. _taskCompletionSource.TrySetResult(true);
  42. Closed?.Invoke(this, EventArgs.Empty);
  43. }
  44. private void OnSocketMessage(SocketHttpListener.MessageEventArgs e)
  45. {
  46. if (OnReceiveBytes != null)
  47. {
  48. OnReceiveBytes(e.RawData);
  49. }
  50. }
  51. public Task ConnectAsServerAsync()
  52. {
  53. return Task.CompletedTask;
  54. }
  55. /// <summary>
  56. /// Gets or sets the state.
  57. /// </summary>
  58. /// <value>The state.</value>
  59. public WebSocketState State => WebSocket.State;
  60. /// <summary>
  61. /// Sends the async.
  62. /// </summary>
  63. /// <param name="bytes">The bytes.</param>
  64. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  65. /// <param name="cancellationToken">The cancellation token.</param>
  66. /// <returns>Task.</returns>
  67. public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  68. {
  69. return WebSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Binary, endOfMessage, cancellationToken);
  70. }
  71. /// <summary>
  72. /// Sends the asynchronous.
  73. /// </summary>
  74. /// <param name="text">The text.</param>
  75. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  76. /// <param name="cancellationToken">The cancellation token.</param>
  77. /// <returns>Task.</returns>
  78. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  79. {
  80. return WebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(text)), WebSocketMessageType.Text, endOfMessage, cancellationToken);
  81. }
  82. /// <summary>
  83. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  84. /// </summary>
  85. public void Dispose()
  86. {
  87. Dispose(true);
  88. GC.SuppressFinalize(this);
  89. }
  90. /// <summary>
  91. /// Releases unmanaged and - optionally - managed resources.
  92. /// </summary>
  93. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  94. protected virtual void Dispose(bool dispose)
  95. {
  96. if (_disposed)
  97. {
  98. return;
  99. }
  100. if (dispose)
  101. {
  102. _cancellationTokenSource.Cancel();
  103. // TODO
  104. // WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "bye", CancellationToken.None).GetAwaiter().GetResult();
  105. }
  106. _disposed = true;
  107. }
  108. /// <summary>
  109. /// Gets or sets the receive action.
  110. /// </summary>
  111. /// <value>The receive action.</value>
  112. public Action<byte[]> OnReceiveBytes { get; set; }
  113. }
  114. }