private async Task SendCloseFrameAsync(WebSocketCloseStatus closeStatus, string closeStatusDescription, CancellationToken cancellationToken)
{
// Close payload is two bytes containing the close status followed by a UTF8-encoding of the status description, if it exists.
byte[] buffer;
if (string.IsNullOrEmpty(closeStatusDescription))
{
buffer = new byte[2];
}
else
{
buffer = new byte[2 + s_textEncoding.GetByteCount(closeStatusDescription)];
int encodedLength = s_textEncoding.GetBytes(closeStatusDescription, 0, closeStatusDescription.Length, buffer, 2);
Debug.Assert(buffer.Length - 2 == encodedLength, $"GetByteCount and GetBytes encoded count didn't match");
}
ushort closeStatusValue = (ushort)closeStatus;
buffer[0] = (byte)(closeStatusValue >> 8);
buffer[1] = (byte)(closeStatusValue & 0xFF);
await SendFrameAsync(MessageOpcode.Close, true, new ArraySegment<byte>(buffer), cancellationToken).ConfigureAwait(false);
lock (StateUpdateLock)
{
_sentCloseFrame = true;
if (_state <= WebSocketState.CloseReceived)
{
_state = WebSocketState.CloseSent;
}
}
}