SharpWebSocket.cs 5.3 KB

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