public async ValueTask CloseAsync(CloseReason closeReason, string message) { var package = new WebSocketPackage(); package.OpCode = OpCode.Close; var bufferSize = !string.IsNullOrEmpty(message) ? _utf8Encoding.GetMaxByteCount(message.Length) : 0; bufferSize += 2; var buffer = GetBuffer(bufferSize); var len = 2; BinaryPrimitives.WriteUInt16BigEndian(buffer, (ushort)package.OpCode); if (!string.IsNullOrEmpty(message)) { len += _utf8Encoding.GetBytes(message, 0, message.Length, buffer, 2); } package.Data = new ReadOnlySequence <byte>(buffer, 0, len); CloseStatus = new CloseStatus { Reason = closeReason, ReasonText = message }; await SendAsync(_packageEncoder, package); State = WebSocketState.CloseSent; var closeHandshakeResponse = await ReceiveAsync(true); if (closeHandshakeResponse.OpCode != OpCode.Close) { OnError($"Unexpected close package, OpCode: {closeHandshakeResponse.OpCode}"); } else { HandleCloseHandshake(closeHandshakeResponse); } await base.CloseAsync(); State = WebSocketState.Closed; }
public async ValueTask CloseAsync(CloseReason closeReason) { await CloseAsync(closeReason, string.Empty); }