-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Add WebSocketStream #114363
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Add WebSocketStream #114363
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
196 changes: 196 additions & 0 deletions
196
src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketStream.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.IO; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace System.Net.WebSockets | ||
{ | ||
/// <summary>Provides a <see cref="Stream"/> that delegates to a wrapped <see cref="WebSocket"/>.</summary> | ||
public sealed class WebSocketStream : Stream | ||
{ | ||
/// <summary>Whether disposing this instance should dispose <see cref="WebSocket"/>.</summary> | ||
private readonly bool _ownsWebSocket; | ||
/// <summary>Whether the instance has been disposed.</summary> | ||
private bool _disposed; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="WebSocketStream"/> class using a specified <see cref="WebSocket"/> instance. | ||
/// </summary> | ||
/// <param name="webSocket">The <see cref="WebSocket"/> wrapped by this instance.</param> | ||
/// <param name="ownsWebSocket"> | ||
/// <see langword="true"/> to indicate that the <see cref="WebSocketStream"/> takes ownership of the <see cref="WebSocket"/>, | ||
/// such that disposing of this <see cref="Stream"/> will dispose of the <see cref="WebSocket"/>; otherwise, <see langword="false"/>. | ||
/// When <see langword="true"/>, disposing of this instance doesn't initiate a close handshake; it merely delegates to | ||
/// <see cref="WebSocket.Dispose"/>. | ||
/// </param> | ||
public WebSocketStream(WebSocket webSocket, bool ownsWebSocket = false) | ||
{ | ||
ArgumentNullException.ThrowIfNull(webSocket); | ||
|
||
WebSocket = webSocket; | ||
_ownsWebSocket = ownsWebSocket; | ||
} | ||
|
||
/// <inheritdoc /> | ||
protected override void Dispose(bool disposing) | ||
{ | ||
if (_disposed) | ||
{ | ||
return; | ||
} | ||
_disposed = true; | ||
|
||
if (disposing && _ownsWebSocket) | ||
{ | ||
if (WebSocket.State is WebSocketState.Open) | ||
{ | ||
// There's no synchronous close, so we're forced to do sync-over-async. | ||
WebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).GetAwaiter().GetResult(); | ||
} | ||
|
||
WebSocket.Dispose(); | ||
} | ||
|
||
base.Dispose(disposing); | ||
} | ||
|
||
/// <inheritdoc /> | ||
public override ValueTask DisposeAsync() | ||
{ | ||
if (_disposed) | ||
{ | ||
return default; | ||
} | ||
_disposed = true; | ||
|
||
if (_ownsWebSocket && WebSocket.State is WebSocketState.Open) | ||
{ | ||
return CloseAndDisposeAsync(); | ||
} | ||
else | ||
{ | ||
return base.DisposeAsync(); | ||
} | ||
|
||
async ValueTask CloseAndDisposeAsync() | ||
{ | ||
if (WebSocket.State is WebSocketState.Open) | ||
{ | ||
await WebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).ConfigureAwait(false); | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
WebSocket.Dispose(); | ||
await base.DisposeAsync().ConfigureAwait(false); | ||
} | ||
} | ||
|
||
/// <summary>Gets the underlying <see cref="WebSocket"/> wrapped by this <see cref="WebSocketStream"/>.</summary> | ||
/// <remarks>The <see cref="WebSocket"/> used to construct this instance.</remarks> | ||
public WebSocket WebSocket { get; } | ||
|
||
/// <inheritdoc /> | ||
public override bool CanRead => WebSocket.State is WebSocketState.Open or WebSocketState.CloseSent; | ||
|
||
/// <inheritdoc /> | ||
public override bool CanWrite => WebSocket.State is WebSocketState.Open or WebSocketState.CloseReceived; | ||
|
||
/// <inheritdoc /> | ||
public override bool CanSeek => false; | ||
|
||
/// <inheritdoc /> | ||
public override void Flush() { } | ||
|
||
/// <inheritdoc /> | ||
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; | ||
|
||
/// <inheritdoc /> | ||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
{ | ||
ValidateBufferArguments(buffer, offset, count); | ||
|
||
return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); | ||
} | ||
|
||
/// <inheritdoc /> | ||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) | ||
{ | ||
ObjectDisposedException.ThrowIf(_disposed, this); | ||
cancellationToken.ThrowIfCancellationRequested(); | ||
|
||
while (WebSocket.State < WebSocketState.CloseReceived) | ||
{ | ||
ValueWebSocketReceiveResult result = await WebSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); | ||
if (result.MessageType == WebSocketMessageType.Close) | ||
{ | ||
break; | ||
} | ||
|
||
if (result.Count > 0 || buffer.IsEmpty) | ||
{ | ||
return result.Count; | ||
} | ||
} | ||
|
||
return 0; | ||
} | ||
|
||
/// <inheritdoc /> | ||
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => | ||
TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count), callback, state); | ||
|
||
/// <inheritdoc /> | ||
public override int EndRead(IAsyncResult asyncResult) => | ||
TaskToAsyncResult.End<int>(asyncResult); | ||
|
||
/// <inheritdoc /> | ||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
{ | ||
ValidateBufferArguments(buffer, offset, count); | ||
|
||
return WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); | ||
} | ||
|
||
/// <inheritdoc /> | ||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) | ||
{ | ||
if (_disposed) | ||
{ | ||
return ValueTask.FromException(new ObjectDisposedException(GetType().FullName)); | ||
} | ||
|
||
if (cancellationToken.IsCancellationRequested) | ||
{ | ||
return ValueTask.FromCanceled(cancellationToken); | ||
} | ||
|
||
return WebSocket.SendAsync(buffer, WebSocketMessageType.Binary, endOfMessage: true, cancellationToken); | ||
} | ||
|
||
/// <inheritdoc /> | ||
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => | ||
TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count), callback, state); | ||
|
||
/// <inheritdoc /> | ||
public override void EndWrite(IAsyncResult asyncResult) => | ||
TaskToAsyncResult.End(asyncResult); | ||
|
||
/// <inheritdoc /> | ||
public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); | ||
|
||
/// <inheritdoc /> | ||
public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); | ||
|
||
/// <inheritdoc /> | ||
public override long Length => throw new NotSupportedException(); | ||
|
||
/// <inheritdoc /> | ||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } | ||
|
||
/// <inheritdoc /> | ||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); | ||
|
||
/// <inheritdoc /> | ||
public override void SetLength(long value) => throw new NotSupportedException(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
src/libraries/System.Net.WebSockets/tests/WebSocketStreamTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.IO; | ||
using System.IO.Tests; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Xunit; | ||
|
||
namespace System.Net.WebSockets.Tests | ||
{ | ||
public sealed class WebSocketStreamTests : ConnectedStreamConformanceTests | ||
{ | ||
protected override bool BlocksOnZeroByteReads => true; | ||
protected override bool FlushRequiredToWriteData => false; | ||
protected override bool ReadsReadUntilSizeOrEof => false; | ||
protected override bool UsableAfterCanceledReads => false; | ||
protected override Type UnsupportedConcurrentExceptionType => null; | ||
|
||
protected override Task<StreamPair> CreateConnectedStreamsAsync() | ||
{ | ||
(Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); | ||
|
||
WebSocket webSocket1 = WebSocket.CreateFromStream(stream1, isServer: false, null, Timeout.InfiniteTimeSpan); | ||
WebSocket webSocket2 = WebSocket.CreateFromStream(stream2, isServer: true, null, Timeout.InfiniteTimeSpan); | ||
|
||
return Task.FromResult(new StreamPair( | ||
new WebSocketStream(webSocket1, ownsWebSocket: true), | ||
new WebSocketStream(webSocket2, ownsWebSocket: true))); | ||
} | ||
|
||
[Fact] | ||
public void Ctor_InvalidArgs_Throws() | ||
{ | ||
AssertExtensions.Throws<ArgumentNullException>("webSocket", () => new WebSocketStream(null)); | ||
AssertExtensions.Throws<ArgumentNullException>("webSocket", () => new WebSocketStream(null, ownsWebSocket: true)); | ||
} | ||
|
||
[Fact] | ||
public void Ctor_Roundtrips() | ||
{ | ||
(Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); | ||
|
||
WebSocket webSocket = WebSocket.CreateFromStream(stream1, isServer: false, null, Timeout.InfiniteTimeSpan); | ||
|
||
WebSocketStream stream = new WebSocketStream(webSocket); | ||
Assert.Same(webSocket, stream.WebSocket); | ||
stream.Dispose(); | ||
Assert.Same(webSocket, stream.WebSocket); | ||
|
||
stream2.Dispose(); | ||
} | ||
|
||
[Theory] | ||
[InlineData(false)] | ||
[InlineData(true)] | ||
public void Dispose_ClosesWebSocketIfOwned(bool ownsWebSocket) | ||
{ | ||
(Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); | ||
|
||
WebSocket webSocket = WebSocket.CreateFromStream(stream1, isServer: false, null, Timeout.InfiniteTimeSpan); | ||
|
||
WebSocketStream stream = new WebSocketStream(webSocket, ownsWebSocket); | ||
Assert.Equal(WebSocketState.Open, webSocket.State); | ||
|
||
stream.Dispose(); | ||
Assert.Equal(ownsWebSocket ? WebSocketState.Closed : WebSocketState.Open, webSocket.State); | ||
|
||
stream2.Dispose(); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.