2016-11-11 19:55:12 +00:00
|
|
|
using System;
|
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
|
|
|
using System.Net;
|
2019-01-13 19:27:29 +00:00
|
|
|
using System.Net.Sockets;
|
2016-11-11 19:55:12 +00:00
|
|
|
using System.Text;
|
|
|
|
using System.Threading;
|
2016-12-13 23:38:26 +00:00
|
|
|
using System.Threading.Tasks;
|
2016-11-11 19:55:12 +00:00
|
|
|
using SocketHttpListener.Net.WebSockets;
|
|
|
|
using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
|
2018-09-12 17:26:21 +00:00
|
|
|
using WebSocketState = System.Net.WebSockets.WebSocketState;
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
namespace SocketHttpListener
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Implements the WebSocket interface.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// The WebSocket class provides a set of methods and properties for two-way communication using
|
|
|
|
/// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
|
|
|
|
/// </remarks>
|
|
|
|
public class WebSocket : IDisposable
|
|
|
|
{
|
|
|
|
#region Private Fields
|
|
|
|
|
|
|
|
private Action _closeContext;
|
|
|
|
private CompressionMethod _compression;
|
|
|
|
private WebSocketContext _context;
|
|
|
|
private CookieCollection _cookies;
|
|
|
|
private AutoResetEvent _exitReceiving;
|
|
|
|
private object _forConn;
|
2019-02-09 14:39:17 +00:00
|
|
|
private readonly SemaphoreSlim _forEvent = new SemaphoreSlim(1, 1);
|
2016-11-11 19:55:12 +00:00
|
|
|
private object _forMessageEventQueue;
|
2019-02-09 14:39:17 +00:00
|
|
|
private readonly SemaphoreSlim _forSend = new SemaphoreSlim(1, 1);
|
2016-11-11 19:55:12 +00:00
|
|
|
private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
|
|
private Queue<MessageEventArgs> _messageEventQueue;
|
|
|
|
private string _protocol;
|
|
|
|
private volatile WebSocketState _readyState;
|
|
|
|
private AutoResetEvent _receivePong;
|
|
|
|
private bool _secure;
|
|
|
|
private Stream _stream;
|
|
|
|
private const string _version = "13";
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Internal Fields
|
|
|
|
|
|
|
|
internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Internal Constructors
|
|
|
|
|
|
|
|
// As server
|
2018-09-12 17:26:21 +00:00
|
|
|
internal WebSocket(string protocol)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
_protocol = protocol;
|
2018-09-12 17:26:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public void SetContext(HttpListenerWebSocketContext context, Action closeContextFn, Stream stream)
|
|
|
|
{
|
|
|
|
_context = context;
|
2016-11-11 19:55:12 +00:00
|
|
|
|
2018-09-12 17:26:21 +00:00
|
|
|
_closeContext = closeContextFn;
|
2016-11-11 19:55:12 +00:00
|
|
|
_secure = context.IsSecureConnection;
|
2018-09-12 17:26:21 +00:00
|
|
|
_stream = stream;
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
init();
|
|
|
|
}
|
|
|
|
|
2019-01-18 15:48:01 +00:00
|
|
|
// In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable default.
|
2019-01-13 20:31:14 +00:00
|
|
|
public static TimeSpan DefaultKeepAliveInterval => TimeSpan.FromSeconds(30);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
2018-09-12 17:26:21 +00:00
|
|
|
#endregion
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the state of the WebSocket connection.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>
|
|
|
|
/// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
|
|
|
|
/// connection. The default value is <see cref="WebSocketState.Connecting"/>.
|
|
|
|
/// </value>
|
2019-01-13 20:31:14 +00:00
|
|
|
public WebSocketState ReadyState => _readyState;
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
#region Public Events
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Occurs when the WebSocket connection has been closed.
|
|
|
|
/// </summary>
|
|
|
|
public event EventHandler<CloseEventArgs> OnClose;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Occurs when the <see cref="WebSocket"/> gets an error.
|
|
|
|
/// </summary>
|
|
|
|
public event EventHandler<ErrorEventArgs> OnError;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Occurs when the <see cref="WebSocket"/> receives a message.
|
|
|
|
/// </summary>
|
|
|
|
public event EventHandler<MessageEventArgs> OnMessage;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Occurs when the WebSocket connection has been established.
|
|
|
|
/// </summary>
|
|
|
|
public event EventHandler OnOpen;
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Private Methods
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task CloseAsync(CloseStatusCode code, string reason, bool wait)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await CloseAsync(new PayloadData(
|
|
|
|
await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)),
|
|
|
|
!code.IsReserved(),
|
|
|
|
wait).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task CloseAsync(PayloadData payload, bool send, bool wait)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
lock (_forConn)
|
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
if (_readyState == WebSocketState.CloseSent || _readyState == WebSocketState.Closed)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-09-12 17:26:21 +00:00
|
|
|
_readyState = WebSocketState.CloseSent;
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
var e = new CloseEventArgs(payload)
|
|
|
|
{
|
|
|
|
WasClean = await CloseHandshakeAsync(
|
2016-11-11 19:55:12 +00:00
|
|
|
send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
|
2019-02-09 14:39:17 +00:00
|
|
|
wait ? 1000 : 0).ConfigureAwait(false)
|
|
|
|
};
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
_readyState = WebSocketState.Closed;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
OnClose.Emit(this, e);
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
error("An exception has occurred while OnClose.", ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> CloseHandshakeAsync(byte[] frameAsBytes, int millisecondsTimeout)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
var sent = frameAsBytes != null && await WriteBytesAsync(frameAsBytes).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
var received =
|
|
|
|
millisecondsTimeout == 0 ||
|
|
|
|
(sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout));
|
|
|
|
|
2018-09-12 17:26:21 +00:00
|
|
|
closeServerResources();
|
|
|
|
|
2016-11-11 19:55:12 +00:00
|
|
|
if (_receivePong != null)
|
|
|
|
{
|
|
|
|
_receivePong.Dispose();
|
|
|
|
_receivePong = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (_exitReceiving != null)
|
|
|
|
{
|
|
|
|
_exitReceiving.Dispose();
|
|
|
|
_exitReceiving = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
var result = sent && received;
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// As server
|
|
|
|
private void closeServerResources()
|
|
|
|
{
|
|
|
|
if (_closeContext == null)
|
|
|
|
return;
|
|
|
|
|
2018-09-12 17:26:21 +00:00
|
|
|
try
|
|
|
|
{
|
|
|
|
_closeContext();
|
|
|
|
}
|
|
|
|
catch (SocketException)
|
|
|
|
{
|
|
|
|
// it could be unable to send the handshake response
|
|
|
|
}
|
|
|
|
|
2016-11-11 19:55:12 +00:00
|
|
|
_closeContext = null;
|
|
|
|
_stream = null;
|
|
|
|
_context = null;
|
|
|
|
}
|
|
|
|
|
2019-02-09 12:41:09 +00:00
|
|
|
private async Task<bool> ConcatenateFragmentsIntoAsync(Stream dest)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
while (true)
|
|
|
|
{
|
2019-02-09 12:41:09 +00:00
|
|
|
var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
if (frame.IsFinal)
|
|
|
|
{
|
|
|
|
/* FINAL */
|
|
|
|
|
|
|
|
// CONT
|
|
|
|
if (frame.IsContinuation)
|
|
|
|
{
|
|
|
|
dest.WriteBytes(frame.PayloadData.ApplicationData);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// PING
|
|
|
|
if (frame.IsPing)
|
|
|
|
{
|
|
|
|
processPingFrame(frame);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// PONG
|
|
|
|
if (frame.IsPong)
|
|
|
|
{
|
|
|
|
processPongFrame(frame);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// CLOSE
|
|
|
|
if (frame.IsClose)
|
2019-02-09 14:39:17 +00:00
|
|
|
return await ProcessCloseFrameAsync(frame).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* MORE */
|
|
|
|
|
|
|
|
// CONT
|
|
|
|
if (frame.IsContinuation)
|
|
|
|
{
|
|
|
|
dest.WriteBytes(frame.PayloadData.ApplicationData);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ?
|
2019-02-09 14:39:17 +00:00
|
|
|
return await ProcessUnsupportedFrameAsync(
|
2016-11-11 19:55:12 +00:00
|
|
|
frame,
|
|
|
|
CloseStatusCode.IncorrectData,
|
2019-02-09 14:39:17 +00:00
|
|
|
"An incorrect data has been received while receiving fragmented data.").ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// As server
|
|
|
|
private HttpResponse createHandshakeCloseResponse(HttpStatusCode code)
|
|
|
|
{
|
|
|
|
var res = HttpResponse.CreateCloseResponse(code);
|
|
|
|
res.Headers["Sec-WebSocket-Version"] = _version;
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
private MessageEventArgs dequeueFromMessageEventQueue()
|
|
|
|
{
|
|
|
|
lock (_forMessageEventQueue)
|
|
|
|
return _messageEventQueue.Count > 0
|
|
|
|
? _messageEventQueue.Dequeue()
|
|
|
|
: null;
|
|
|
|
}
|
|
|
|
|
|
|
|
private void enqueueToMessageEventQueue(MessageEventArgs e)
|
|
|
|
{
|
|
|
|
lock (_forMessageEventQueue)
|
|
|
|
_messageEventQueue.Enqueue(e);
|
|
|
|
}
|
|
|
|
|
|
|
|
private void error(string message, Exception exception)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (exception != null)
|
|
|
|
{
|
|
|
|
message += ". Exception.Message: " + exception.Message;
|
|
|
|
}
|
|
|
|
OnError.Emit(this, new ErrorEventArgs(message));
|
|
|
|
}
|
2018-12-15 18:53:09 +00:00
|
|
|
catch (Exception)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private void error(string message)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
OnError.Emit(this, new ErrorEventArgs(message));
|
|
|
|
}
|
2018-12-15 18:53:09 +00:00
|
|
|
catch (Exception)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private void init()
|
|
|
|
{
|
|
|
|
_compression = CompressionMethod.None;
|
|
|
|
_cookies = new CookieCollection();
|
|
|
|
_forConn = new object();
|
|
|
|
_messageEventQueue = new Queue<MessageEventArgs>();
|
|
|
|
_forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
|
|
|
|
_readyState = WebSocketState.Connecting;
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task OpenAsync()
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
startReceiving();
|
|
|
|
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await ProcessExceptionAsync(ex, "An exception has occurred while opening.").ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
await _forEvent.WaitAsync().ConfigureAwait(false);
|
|
|
|
try
|
|
|
|
{
|
|
|
|
OnOpen?.Invoke(this, EventArgs.Empty);
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
await ProcessExceptionAsync(ex, "An exception has occurred while OnOpen.").ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
_forEvent.Release();
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> ProcessCloseFrameAsync(WebSocketFrame frame)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
var payload = frame.PayloadData;
|
2019-02-09 14:39:17 +00:00
|
|
|
await CloseAsync(payload, !payload.ContainsReservedCloseStatusCode, false).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private bool processDataFrame(WebSocketFrame frame)
|
|
|
|
{
|
|
|
|
var e = frame.IsCompressed
|
|
|
|
? new MessageEventArgs(
|
|
|
|
frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression))
|
|
|
|
: new MessageEventArgs(frame.Opcode, frame.PayloadData);
|
|
|
|
|
|
|
|
enqueueToMessageEventQueue(e);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task ProcessExceptionAsync(Exception exception, string message)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
var code = CloseStatusCode.Abnormal;
|
|
|
|
var reason = message;
|
|
|
|
if (exception is WebSocketException)
|
|
|
|
{
|
|
|
|
var wsex = (WebSocketException)exception;
|
|
|
|
code = wsex.Code;
|
|
|
|
reason = wsex.Message;
|
|
|
|
}
|
|
|
|
|
|
|
|
error(message ?? code.GetMessage(), exception);
|
|
|
|
if (_readyState == WebSocketState.Connecting)
|
2019-02-09 14:39:17 +00:00
|
|
|
{
|
|
|
|
await CloseAsync(HttpStatusCode.BadRequest).ConfigureAwait(false);
|
|
|
|
}
|
2016-11-11 19:55:12 +00:00
|
|
|
else
|
2019-02-09 14:39:17 +00:00
|
|
|
{
|
|
|
|
await CloseAsync(code, reason ?? code.GetMessage(), false).ConfigureAwait(false);
|
|
|
|
}
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 12:41:09 +00:00
|
|
|
private Task<bool> ProcessFragmentedFrameAsync(WebSocketFrame frame)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
return frame.IsContinuation // Not first fragment
|
2019-02-09 12:41:09 +00:00
|
|
|
? Task.FromResult(true)
|
|
|
|
: ProcessFragmentsAsync(frame);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 12:41:09 +00:00
|
|
|
private async Task<bool> ProcessFragmentsAsync(WebSocketFrame first)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
using (var buff = new MemoryStream())
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
buff.WriteBytes(first.PayloadData.ApplicationData);
|
2019-02-09 12:41:09 +00:00
|
|
|
if (!await ConcatenateFragmentsIntoAsync(buff).ConfigureAwait(false))
|
|
|
|
{
|
2016-11-11 19:55:12 +00:00
|
|
|
return false;
|
2019-02-09 12:41:09 +00:00
|
|
|
}
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
byte[] data;
|
|
|
|
if (_compression != CompressionMethod.None)
|
|
|
|
{
|
|
|
|
data = buff.DecompressToArray(_compression);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
data = buff.ToArray();
|
|
|
|
}
|
|
|
|
|
|
|
|
enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private bool processPingFrame(WebSocketFrame frame)
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
private bool processPongFrame(WebSocketFrame frame)
|
|
|
|
{
|
|
|
|
_receivePong.Set();
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> ProcessUnsupportedFrameAsync(WebSocketFrame frame, CloseStatusCode code, string reason)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await ProcessExceptionAsync(new WebSocketException(code, reason), null).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private Task<bool> ProcessWebSocketFrameAsync(WebSocketFrame frame)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2019-02-20 11:53:35 +00:00
|
|
|
// TODO: @bond change to if/else chain
|
2016-11-11 19:55:12 +00:00
|
|
|
return frame.IsCompressed && _compression == CompressionMethod.None
|
2019-02-09 14:39:17 +00:00
|
|
|
? ProcessUnsupportedFrameAsync(
|
2016-11-11 19:55:12 +00:00
|
|
|
frame,
|
|
|
|
CloseStatusCode.IncorrectData,
|
|
|
|
"A compressed data has been received without available decompression method.")
|
|
|
|
: frame.IsFragmented
|
2019-02-09 14:39:17 +00:00
|
|
|
? ProcessFragmentedFrameAsync(frame)
|
2016-11-11 19:55:12 +00:00
|
|
|
: frame.IsData
|
2019-02-09 14:39:17 +00:00
|
|
|
? Task.FromResult(processDataFrame(frame))
|
2016-11-11 19:55:12 +00:00
|
|
|
: frame.IsPing
|
2019-02-09 14:39:17 +00:00
|
|
|
? Task.FromResult(processPingFrame(frame))
|
2016-11-11 19:55:12 +00:00
|
|
|
: frame.IsPong
|
2019-02-09 14:39:17 +00:00
|
|
|
? Task.FromResult(processPongFrame(frame))
|
2016-11-11 19:55:12 +00:00
|
|
|
: frame.IsClose
|
2019-02-09 14:39:17 +00:00
|
|
|
? ProcessCloseFrameAsync(frame)
|
|
|
|
: ProcessUnsupportedFrameAsync(frame, CloseStatusCode.PolicyViolation, null);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> SendAsync(Opcode opcode, Stream stream)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await _forSend.WaitAsync().ConfigureAwait(false);
|
|
|
|
try
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
var src = stream;
|
|
|
|
var compressed = false;
|
|
|
|
var sent = false;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (_compression != CompressionMethod.None)
|
|
|
|
{
|
|
|
|
stream = stream.Compress(_compression);
|
|
|
|
compressed = true;
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
sent = await SendAsync(opcode, Mask.Unmask, stream, compressed).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
if (!sent)
|
|
|
|
error("Sending a data has been interrupted.");
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
error("An exception has occurred while sending a data.", ex);
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
if (compressed)
|
|
|
|
stream.Dispose();
|
|
|
|
|
|
|
|
src.Dispose();
|
|
|
|
}
|
|
|
|
|
|
|
|
return sent;
|
|
|
|
}
|
2019-02-09 14:39:17 +00:00
|
|
|
finally
|
|
|
|
{
|
|
|
|
_forSend.Release();
|
|
|
|
}
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> SendAsync(Opcode opcode, Mask mask, Stream stream, bool compressed)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
var len = stream.Length;
|
|
|
|
|
|
|
|
/* Not fragmented */
|
|
|
|
|
|
|
|
if (len == 0)
|
2019-02-09 14:39:17 +00:00
|
|
|
return await SendAsync(Fin.Final, opcode, mask, new byte[0], compressed).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
var quo = len / FragmentLength;
|
|
|
|
var rem = (int)(len % FragmentLength);
|
|
|
|
|
|
|
|
byte[] buff = null;
|
|
|
|
if (quo == 0)
|
|
|
|
{
|
|
|
|
buff = new byte[rem];
|
2019-02-09 14:39:17 +00:00
|
|
|
return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
|
|
|
|
await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
buff = new byte[FragmentLength];
|
|
|
|
if (quo == 1 && rem == 0)
|
2019-02-09 14:39:17 +00:00
|
|
|
return await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) == FragmentLength &&
|
|
|
|
await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
/* Send fragmented */
|
|
|
|
|
|
|
|
// Begin
|
2019-02-09 14:39:17 +00:00
|
|
|
if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
|
|
|
|
!await SendAsync(Fin.More, opcode, mask, buff, compressed).ConfigureAwait(false))
|
2016-11-11 19:55:12 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
var n = rem == 0 ? quo - 2 : quo - 1;
|
|
|
|
for (long i = 0; i < n; i++)
|
2019-02-09 14:39:17 +00:00
|
|
|
if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
|
|
|
|
!await SendAsync(Fin.More, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false))
|
2016-11-11 19:55:12 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
// End
|
|
|
|
if (rem == 0)
|
|
|
|
rem = FragmentLength;
|
|
|
|
else
|
|
|
|
buff = new byte[rem];
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
|
|
|
|
await SendAsync(Fin.Final, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private Task<bool> SendAsync(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
lock (_forConn)
|
|
|
|
{
|
|
|
|
if (_readyState != WebSocketState.Open)
|
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
return Task.FromResult(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
return WriteBytesAsync(
|
2016-11-11 19:55:12 +00:00
|
|
|
WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// As server
|
2019-02-09 14:39:17 +00:00
|
|
|
private Task<bool> SendHttpResponseAsync(HttpResponse response)
|
|
|
|
=> WriteBytesAsync(response.ToByteArray());
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
private void startReceiving()
|
|
|
|
{
|
|
|
|
if (_messageEventQueue.Count > 0)
|
2019-02-09 12:41:09 +00:00
|
|
|
{
|
2016-11-11 19:55:12 +00:00
|
|
|
_messageEventQueue.Clear();
|
2019-02-09 12:41:09 +00:00
|
|
|
}
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
_exitReceiving = new AutoResetEvent(false);
|
|
|
|
_receivePong = new AutoResetEvent(false);
|
|
|
|
|
|
|
|
Action receive = null;
|
2019-02-09 12:41:09 +00:00
|
|
|
receive = async () => await WebSocketFrame.ReadAsync(
|
|
|
|
_stream,
|
|
|
|
true,
|
|
|
|
async frame =>
|
|
|
|
{
|
|
|
|
if (await ProcessWebSocketFrameAsync(frame).ConfigureAwait(false) && _readyState != WebSocketState.Closed)
|
|
|
|
{
|
|
|
|
receive();
|
|
|
|
|
|
|
|
if (!frame.IsData)
|
2019-02-09 14:39:17 +00:00
|
|
|
{
|
2019-02-09 12:41:09 +00:00
|
|
|
return;
|
2019-02-09 14:39:17 +00:00
|
|
|
}
|
2019-02-09 12:41:09 +00:00
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
await _forEvent.WaitAsync().ConfigureAwait(false);
|
|
|
|
|
|
|
|
try
|
2019-02-09 12:41:09 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
var e = dequeueFromMessageEventQueue();
|
|
|
|
if (e != null && _readyState == WebSocketState.Open)
|
2019-02-09 12:41:09 +00:00
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
OnMessage.Emit(this, e);
|
2019-02-09 12:41:09 +00:00
|
|
|
}
|
|
|
|
}
|
2019-02-09 14:39:17 +00:00
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
await ProcessExceptionAsync(ex, "An exception has occurred while OnMessage.").ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
_forEvent.Release();
|
|
|
|
}
|
|
|
|
|
2019-02-09 12:41:09 +00:00
|
|
|
}
|
|
|
|
else if (_exitReceiving != null)
|
|
|
|
{
|
|
|
|
_exitReceiving.Set();
|
|
|
|
}
|
|
|
|
},
|
2019-02-09 14:39:17 +00:00
|
|
|
async ex => await ProcessExceptionAsync(ex, "An exception has occurred while receiving a message.")).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
receive();
|
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
private async Task<bool> WriteBytesAsync(byte[] data)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await _stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
return true;
|
|
|
|
}
|
2018-09-12 17:26:21 +00:00
|
|
|
catch (Exception)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Internal Methods
|
|
|
|
|
|
|
|
// As server
|
2019-02-09 14:39:17 +00:00
|
|
|
internal async Task CloseAsync(HttpResponse response)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
_readyState = WebSocketState.CloseSent;
|
2019-02-09 14:39:17 +00:00
|
|
|
await SendHttpResponseAsync(response).ConfigureAwait(false);
|
2018-09-12 17:26:21 +00:00
|
|
|
|
2016-11-11 19:55:12 +00:00
|
|
|
closeServerResources();
|
|
|
|
|
|
|
|
_readyState = WebSocketState.Closed;
|
|
|
|
}
|
|
|
|
|
|
|
|
// As server
|
2019-02-09 14:39:17 +00:00
|
|
|
internal Task CloseAsync(HttpStatusCode code)
|
|
|
|
=> CloseAsync(createHandshakeCloseResponse(code));
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
// As server
|
2019-02-09 14:39:17 +00:00
|
|
|
public async Task ConnectAsServer()
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
_readyState = WebSocketState.Open;
|
2019-02-09 14:39:17 +00:00
|
|
|
await OpenAsync().ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
await ProcessExceptionAsync(ex, "An exception has occurred while connecting.").ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Public Methods
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Closes the WebSocket connection, and releases all associated resources.
|
|
|
|
/// </summary>
|
2019-02-09 14:39:17 +00:00
|
|
|
public Task CloseAsync()
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
var msg = _readyState.CheckIfClosable();
|
|
|
|
if (msg != null)
|
|
|
|
{
|
|
|
|
error(msg);
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
return Task.CompletedTask;
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var send = _readyState == WebSocketState.Open;
|
2019-02-09 14:39:17 +00:00
|
|
|
return CloseAsync(new PayloadData(), send, send);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
|
|
|
|
/// and <see cref="string"/>, and releases all associated resources.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// This method emits a <see cref="OnError"/> event if the size
|
|
|
|
/// of <paramref name="reason"/> is greater than 123 bytes.
|
|
|
|
/// </remarks>
|
|
|
|
/// <param name="code">
|
|
|
|
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
|
|
|
|
/// indicating the reason for the close.
|
|
|
|
/// </param>
|
|
|
|
/// <param name="reason">
|
|
|
|
/// A <see cref="string"/> that represents the reason for the close.
|
|
|
|
/// </param>
|
2019-02-09 14:39:17 +00:00
|
|
|
public async Task CloseAsync(CloseStatusCode code, string reason)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
|
|
|
byte[] data = null;
|
|
|
|
var msg = _readyState.CheckIfClosable() ??
|
2019-02-09 14:39:17 +00:00
|
|
|
(data = await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)).CheckIfValidControlData("reason");
|
2016-11-11 19:55:12 +00:00
|
|
|
|
|
|
|
if (msg != null)
|
|
|
|
{
|
|
|
|
error(msg);
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var send = _readyState == WebSocketState.Open && !code.IsReserved();
|
2019-02-09 14:39:17 +00:00
|
|
|
await CloseAsync(new PayloadData(data), send, send).ConfigureAwait(false);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// This method doesn't wait for the send to be complete.
|
|
|
|
/// </remarks>
|
|
|
|
/// <param name="data">
|
|
|
|
/// An array of <see cref="byte"/> that represents the binary data to send.
|
|
|
|
/// </param>
|
2016-12-13 23:38:26 +00:00
|
|
|
public Task SendAsync(byte[] data)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
if (data == null)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
throw new ArgumentNullException(nameof(data));
|
2018-09-12 17:26:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var msg = _readyState.CheckIfOpen();
|
2016-11-11 19:55:12 +00:00
|
|
|
if (msg != null)
|
|
|
|
{
|
2016-12-13 23:38:26 +00:00
|
|
|
throw new Exception(msg);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
return SendAsync(Opcode.Binary, new MemoryStream(data));
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// This method doesn't wait for the send to be complete.
|
|
|
|
/// </remarks>
|
|
|
|
/// <param name="data">
|
|
|
|
/// A <see cref="string"/> that represents the text data to send.
|
|
|
|
/// </param>
|
2016-12-13 23:38:26 +00:00
|
|
|
public Task SendAsync(string data)
|
2016-11-11 19:55:12 +00:00
|
|
|
{
|
2018-09-12 17:26:21 +00:00
|
|
|
if (data == null)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
throw new ArgumentNullException(nameof(data));
|
2018-09-12 17:26:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var msg = _readyState.CheckIfOpen();
|
2016-11-11 19:55:12 +00:00
|
|
|
if (msg != null)
|
|
|
|
{
|
2016-12-13 23:38:26 +00:00
|
|
|
throw new Exception(msg);
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 14:39:17 +00:00
|
|
|
return SendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Explicit Interface Implementation
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Closes the WebSocket connection, and releases all associated resources.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
|
|
|
|
/// </remarks>
|
|
|
|
void IDisposable.Dispose()
|
|
|
|
{
|
2019-02-09 14:39:17 +00:00
|
|
|
CloseAsync(CloseStatusCode.Away, null).GetAwaiter().GetResult();
|
2016-11-11 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
}
|
2018-12-15 18:53:09 +00:00
|
|
|
}
|