/// <summary> /// Closes the WebSocket connection using the close handshake defined in the /// WebSocket protocol specification section 7. /// </summary> /// <param name="closeStatus">Indicates the reason for closing the WebSocket connection.</param> /// <param name="statusDescription">Specifies a human readable explanation as to why the connection is closed.</param> /// <param name="cancellationToken">The token that can be used to propagate notification that operations should be canceled.</param> /// <returns>Returns System.Threading.Tasks.Task.</returns> public Task CloseAsync(CloseCodeStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { // Create a new task. return(Task.Factory.StartNew(() => { try { // Check can be closed. var msg = _readyState.CheckIfClosable() ?? closeStatus.CheckIfValidCloseParameters(statusDescription); if (!String.IsNullOrEmpty(msg)) { return; } // If cancellation has not been requested. if (!cancellationToken.IsCancellationRequested) { // If no status code. if (closeStatus.IsNoStatusCode()) { // Close the connection. Close(new CloseEventArgs(), true, true); return; } // Close the connection. var send = !closeStatus.IsReserved(); Close(new CloseEventArgs(closeStatus, statusDescription), send, send); } } catch { } }, cancellationToken)); }
/// <summary> /// Check if valid close parameters. /// </summary> /// <param name="code">The code.</param> /// <param name="reason">The reason.</param> /// <returns>The message.</returns> public static string CheckIfValidCloseParameters(this CloseCodeStatus code, string reason) { return(code.IsNoStatusCode() && !reason.IsNullOrEmpty() ? "NoStatusCode cannot have a reason." : !reason.IsNullOrEmpty() && Encoding.UTF8.GetBytes(reason).Length > 123 ? "A reason has greater than the allowable max size." : null); }