SharpWebSocket.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using System.Text;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using WebSocketMessageType = MediaBrowser.Model.Net.WebSocketMessageType;
  9. using WebSocketState = MediaBrowser.Model.Net.WebSocketState;
  10. namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp
  11. {
  12. public class SharpWebSocket : IWebSocket
  13. {
  14. /// <summary>
  15. /// The logger
  16. /// </summary>
  17. private readonly ILogger _logger;
  18. public event EventHandler<EventArgs> Closed;
  19. /// <summary>
  20. /// Gets or sets the web socket.
  21. /// </summary>
  22. /// <value>The web socket.</value>
  23. private WebSocketSharp.WebSocket WebSocket { get; set; }
  24. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="NativeWebSocket" /> class.
  27. /// </summary>
  28. /// <param name="socket">The socket.</param>
  29. /// <param name="logger">The logger.</param>
  30. /// <exception cref="System.ArgumentNullException">socket</exception>
  31. public SharpWebSocket(WebSocketSharp.WebSocket socket, ILogger logger)
  32. {
  33. if (socket == null)
  34. {
  35. throw new ArgumentNullException("socket");
  36. }
  37. if (logger == null)
  38. {
  39. throw new ArgumentNullException("logger");
  40. }
  41. _logger = logger;
  42. WebSocket = socket;
  43. socket.OnMessage += socket_OnMessage;
  44. socket.OnClose += socket_OnClose;
  45. socket.OnError += socket_OnError;
  46. WebSocket.ConnectAsServer();
  47. }
  48. void socket_OnError(object sender, WebSocketSharp.ErrorEventArgs e)
  49. {
  50. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  51. }
  52. void socket_OnClose(object sender, WebSocketSharp.CloseEventArgs e)
  53. {
  54. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  55. }
  56. void socket_OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
  57. {
  58. if (OnReceive != null)
  59. {
  60. OnReceiveBytes(e.RawData);
  61. }
  62. }
  63. /// <summary>
  64. /// Gets or sets the state.
  65. /// </summary>
  66. /// <value>The state.</value>
  67. public WebSocketState State
  68. {
  69. get
  70. {
  71. WebSocketState commonState;
  72. if (!Enum.TryParse(WebSocket.ReadyState.ToString(), true, out commonState))
  73. {
  74. _logger.Warn("Unrecognized WebSocketState: {0}", WebSocket.ReadyState.ToString());
  75. }
  76. return commonState;
  77. }
  78. }
  79. /// <summary>
  80. /// Sends the async.
  81. /// </summary>
  82. /// <param name="bytes">The bytes.</param>
  83. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task.</returns>
  86. public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  87. {
  88. var completionSource = new TaskCompletionSource<bool>();
  89. WebSocket.SendAsync(bytes, res => completionSource.TrySetResult(true));
  90. return completionSource.Task;
  91. }
  92. /// <summary>
  93. /// Sends the asynchronous.
  94. /// </summary>
  95. /// <param name="text">The text.</param>
  96. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  97. /// <param name="cancellationToken">The cancellation token.</param>
  98. /// <returns>Task.</returns>
  99. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  100. {
  101. var completionSource = new TaskCompletionSource<bool>();
  102. WebSocket.SendAsync(text, res => completionSource.TrySetResult(true));
  103. return completionSource.Task;
  104. }
  105. /// <summary>
  106. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  107. /// </summary>
  108. public void Dispose()
  109. {
  110. Dispose(true);
  111. }
  112. /// <summary>
  113. /// Releases unmanaged and - optionally - managed resources.
  114. /// </summary>
  115. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  116. protected virtual void Dispose(bool dispose)
  117. {
  118. if (dispose)
  119. {
  120. WebSocket.OnMessage -= socket_OnMessage;
  121. WebSocket.OnClose -= socket_OnClose;
  122. WebSocket.OnError -= socket_OnError;
  123. _cancellationTokenSource.Cancel();
  124. WebSocket.Close();
  125. }
  126. }
  127. /// <summary>
  128. /// Gets or sets the receive action.
  129. /// </summary>
  130. /// <value>The receive action.</value>
  131. public Action<byte[]> OnReceiveBytes { get; set; }
  132. /// <summary>
  133. /// Gets or sets the on receive.
  134. /// </summary>
  135. /// <value>The on receive.</value>
  136. public Action<string> OnReceive { get; set; }
  137. }
  138. }