2
0

SharpWebSocket.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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="type">The type.</param>
  84. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  85. /// <param name="cancellationToken">The cancellation token.</param>
  86. /// <returns>Task.</returns>
  87. public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
  88. {
  89. System.Net.WebSockets.WebSocketMessageType nativeType;
  90. if (!Enum.TryParse(type.ToString(), true, out nativeType))
  91. {
  92. _logger.Warn("Unrecognized WebSocketMessageType: {0}", type.ToString());
  93. }
  94. var completionSource = new TaskCompletionSource<bool>();
  95. WebSocket.SendAsync(Encoding.UTF8.GetString(bytes), res => completionSource.TrySetResult(true));
  96. return completionSource.Task;
  97. }
  98. /// <summary>
  99. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  100. /// </summary>
  101. public void Dispose()
  102. {
  103. Dispose(true);
  104. }
  105. /// <summary>
  106. /// Releases unmanaged and - optionally - managed resources.
  107. /// </summary>
  108. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  109. protected virtual void Dispose(bool dispose)
  110. {
  111. if (dispose)
  112. {
  113. WebSocket.OnMessage -= socket_OnMessage;
  114. WebSocket.OnClose -= socket_OnClose;
  115. WebSocket.OnError -= socket_OnError;
  116. _cancellationTokenSource.Cancel();
  117. WebSocket.Close();
  118. }
  119. }
  120. /// <summary>
  121. /// Gets or sets the receive action.
  122. /// </summary>
  123. /// <value>The receive action.</value>
  124. public Action<byte[]> OnReceiveBytes { get; set; }
  125. /// <summary>
  126. /// Gets or sets the on receive.
  127. /// </summary>
  128. /// <value>The on receive.</value>
  129. public Action<string> OnReceive { get; set; }
  130. }
  131. }