jellyfin/MediaBrowser.Server.Implementations/HttpServer/NativeWebSocket.cs

241 lines
7.9 KiB
C#
Raw Normal View History

2014-07-20 04:46:29 +00:00
using System.Text;
using MediaBrowser.Common.Events;
2014-05-17 18:37:40 +00:00
using MediaBrowser.Common.Net;
2013-02-25 00:13:45 +00:00
using MediaBrowser.Model.Logging;
2013-02-21 01:33:05 +00:00
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using WebSocketMessageType = MediaBrowser.Model.Net.WebSocketMessageType;
using WebSocketState = MediaBrowser.Model.Net.WebSocketState;
2013-02-21 01:33:05 +00:00
2013-03-07 05:34:00 +00:00
namespace MediaBrowser.Server.Implementations.HttpServer
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Class NativeWebSocket
/// </summary>
public class NativeWebSocket : IWebSocket
{
/// <summary>
/// The logger
/// </summary>
2013-02-21 21:06:23 +00:00
private readonly ILogger _logger;
2013-02-21 01:33:05 +00:00
2014-05-17 18:37:40 +00:00
public event EventHandler<EventArgs> Closed;
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets or sets the web socket.
/// </summary>
/// <value>The web socket.</value>
2013-02-25 00:13:45 +00:00
private System.Net.WebSockets.WebSocket WebSocket { get; set; }
2013-02-21 01:33:05 +00:00
2013-09-30 01:29:38 +00:00
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
2013-02-21 01:33:05 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="NativeWebSocket" /> class.
/// </summary>
/// <param name="socket">The socket.</param>
2013-02-21 21:06:23 +00:00
/// <param name="logger">The logger.</param>
2013-02-21 01:33:05 +00:00
/// <exception cref="System.ArgumentNullException">socket</exception>
2014-07-20 04:46:29 +00:00
public NativeWebSocket(WebSocket socket, ILogger logger)
2013-02-21 01:33:05 +00:00
{
if (socket == null)
{
throw new ArgumentNullException("socket");
}
2013-02-21 21:06:23 +00:00
if (logger == null)
{
throw new ArgumentNullException("logger");
}
_logger = logger;
2013-02-21 01:33:05 +00:00
WebSocket = socket;
Receive();
}
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State
{
2013-02-25 00:13:45 +00:00
get
{
WebSocketState commonState;
if (!Enum.TryParse(WebSocket.State.ToString(), true, out commonState))
{
_logger.Warn("Unrecognized WebSocketState: {0}", WebSocket.State.ToString());
}
return commonState;
}
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Receives this instance.
/// </summary>
private async void Receive()
{
while (true)
{
byte[] bytes;
try
{
bytes = await ReceiveBytesAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
2013-02-21 01:33:05 +00:00
}
catch (OperationCanceledException)
{
break;
}
2013-02-21 01:33:05 +00:00
catch (WebSocketException ex)
{
_logger.ErrorException("Error receiving web socket message", ex);
2013-02-21 01:33:05 +00:00
break;
}
if (bytes == null)
{
// Connection closed
2014-05-17 18:37:40 +00:00
EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
break;
}
if (OnReceiveBytes != null)
2013-02-21 01:33:05 +00:00
{
OnReceiveBytes(bytes);
2013-02-21 01:33:05 +00:00
}
}
}
/// <summary>
/// Receives the async.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{WebSocketMessageInfo}.</returns>
/// <exception cref="System.Net.WebSockets.WebSocketException">Connection closed</exception>
private async Task<byte[]> ReceiveBytesAsync(CancellationToken cancellationToken)
{
var bytes = new byte[4096];
var buffer = new ArraySegment<byte>(bytes);
var result = await WebSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
if (result.CloseStatus.HasValue)
2013-02-21 01:33:05 +00:00
{
_logger.Info("Web socket connection closed by client. Reason: {0}", result.CloseStatus.Value);
return null;
2013-02-21 01:33:05 +00:00
}
return buffer.Array;
}
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="type">The type.</param>
/// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
{
2013-02-25 00:13:45 +00:00
System.Net.WebSockets.WebSocketMessageType nativeType;
if (!Enum.TryParse(type.ToString(), true, out nativeType))
{
_logger.Warn("Unrecognized WebSocketMessageType: {0}", type.ToString());
}
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), nativeType, true, linkedTokenSource.Token);
2013-02-21 01:33:05 +00:00
}
2014-07-20 04:46:29 +00:00
public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), System.Net.WebSockets.WebSocketMessageType.Binary, true, linkedTokenSource.Token);
}
public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
var bytes = Encoding.UTF8.GetBytes(text);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), System.Net.WebSockets.WebSocketMessageType.Text, true, linkedTokenSource.Token);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
_cancellationTokenSource.Cancel();
2013-02-21 01:33:05 +00:00
WebSocket.Dispose();
}
}
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Action<byte[]> OnReceiveBytes { get; set; }
/// <summary>
/// Gets or sets the on receive.
/// </summary>
/// <value>The on receive.</value>
public Action<string> OnReceive { get; set; }
2013-12-07 15:52:38 +00:00
/// <summary>
/// The _supports native web socket
/// </summary>
private static bool? _supportsNativeWebSocket;
/// <summary>
/// Gets a value indicating whether [supports web sockets].
/// </summary>
/// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
public static bool IsSupported
{
get
{
if (!_supportsNativeWebSocket.HasValue)
{
try
{
new ClientWebSocket();
_supportsNativeWebSocket = true;
}
catch (PlatformNotSupportedException)
{
_supportsNativeWebSocket = false;
}
}
return _supportsNativeWebSocket.Value;
}
}
2013-02-21 01:33:05 +00:00
}
}