Skip to content
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

[release/8.0][browser] WebSocket works differently depending on if we look up its state or not #99673

Merged
merged 4 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ await socket.CloseAsync(
{
await Task.Delay(5000);
}
else if (receivedMessage == ".receiveMessageAfterClose")
{
byte[] buffer = new byte[1024];
string message = $"{receivedMessage} {DateTime.Now.ToString("HH:mm:ss")}";
buffer = System.Text.Encoding.UTF8.GetBytes(message);
await socket.SendAsync(
new ArraySegment<byte>(buffer, 0, message.Length),
WebSocketMessageType.Text,
true,
CancellationToken.None);
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, receivedMessage, CancellationToken.None);
}
else if (socket.State == WebSocketState.Open)
{
sendMessage = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ internal static partial class BrowserInterop
public static int GetReadyState(JSObject? webSocket)
{
if (webSocket == null || webSocket.IsDisposed) return -1;
int? readyState = webSocket.GetPropertyAsInt32("readyState");
if (!readyState.HasValue) return -1;
return readyState.Value;
return BrowserInterop.WebSocketGetState(webSocket);
}

[JSImport("INTERNAL.ws_get_state")]
public static partial int WebSocketGetState(
JSObject webSocket);

[JSImport("INTERNAL.ws_wasm_create")]
public static partial JSObject WebSocketCreate(
string uri,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,6 @@ private void CreateCore(Uri uri, List<string>? requestedSubProtocols)
#endif
_closeStatus = (WebSocketCloseStatus)code;
_closeStatusDescription = reason;
_closeReceived = true;
WebSocketState state = State;
if (state == WebSocketState.Connecting || state == WebSocketState.Open || state == WebSocketState.CloseSent)
{
FastState = WebSocketState.Closed;
}
#if FEATURE_WASM_THREADS
} //lock
#endif
Expand Down
46 changes: 44 additions & 2 deletions src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;

using Xunit;
using Xunit.Abstractions;
Expand Down Expand Up @@ -264,8 +265,8 @@ public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri serve

[ActiveIssue("https://github.com/dotnet/runtime/issues/28957", typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ServerInitiated_CanReceive(Uri server)
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServersWithSwitch))]
public async Task CloseOutputAsync_ServerInitiated_CanReceive(Uri server, bool delayReceiving)
{
string message = "Hello WebSockets!";
var expectedCloseStatus = WebSocketCloseStatus.NormalClosure;
Expand All @@ -281,6 +282,10 @@ await cws.SendAsync(
true,
cts.Token);

// let server close the output before we request receiving
if (delayReceiving)
await Task.Delay(1000);

// Should be able to receive the message echoed by the server.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
Expand Down Expand Up @@ -367,6 +372,43 @@ await cws.SendAsync(
}
}

public static IEnumerable<object[]> EchoServersWithSwitch =>
EchoServers.SelectMany(server => new List<object[]>
{
new object[] { server[0], true },
new object[] { server[0], false }
});

[ActiveIssue("https://github.com/dotnet/runtime/issues/28957", typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServersWithSwitch))]
public async Task CloseOutputAsync_ServerInitiated_CanReceiveAfterClose(Uri server, bool syncState)
{
using (ClientWebSocket cws = await GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".receiveMessageAfterClose"),
WebSocketMessageType.Text,
true,
cts.Token);

await Task.Delay(2000);

if (syncState)
{
var state = cws.State;
Assert.Equal(WebSocketState.Open, state);
// should be able to receive after this sync
}

var recvBuffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(recvBuffer, cts.Token);
var message = Encoding.UTF8.GetString(recvBuffer.ToArray(), 0, recvResult.Count);

Assert.Contains(".receiveMessageAfterClose", message);
}
}

[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
Expand Down
3 changes: 2 additions & 1 deletion src/mono/wasm/runtime/exports-internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { http_wasm_supports_streaming_response, http_wasm_create_abort_controler
import { exportedRuntimeAPI, Module, runtimeHelpers } from "./globals";
import { get_property, set_property, has_property, get_typeof_property, get_global_this, dynamic_import } from "./invoke-js";
import { mono_wasm_stringify_as_error_with_stack } from "./logging";
import { ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort } from "./web-socket";
import { ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort, ws_get_state } from "./web-socket";
import { mono_wasm_get_loaded_files } from "./assets";
import { jiterpreter_dump_stats } from "./jiterpreter";
import { getOptions, applyOptions } from "./jiterpreter-support";
Expand Down Expand Up @@ -62,6 +62,7 @@ export function export_internal(): any {
ws_wasm_receive,
ws_wasm_close,
ws_wasm_abort,
ws_get_state,

// BrowserHttpHandler
http_wasm_supports_streaming_response,
Expand Down
14 changes: 12 additions & 2 deletions src/mono/wasm/runtime/web-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ function verifyEnvironment() {
}
}

export function ws_get_state(ws: WebSocketExtension) : number
{
if (ws.readyState != WebSocket.CLOSED)
return ws.readyState ?? -1;
const receive_event_queue = ws[wasm_ws_pending_receive_event_queue];
const queued_events_count = receive_event_queue.getLength();
if (queued_events_count == 0)
return ws.readyState ?? -1;
return WebSocket.OPEN;
}

export function ws_wasm_create(uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr, onClosed: (code: number, reason: string) => void): WebSocketExtension {
verifyEnvironment();
mono_assert(uri && typeof uri === "string", () => `ERR12: Invalid uri ${typeof uri}`);
Expand Down Expand Up @@ -175,8 +186,7 @@ export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buf
return null;
}

const readyState = ws.readyState;
if (readyState == WebSocket.CLOSED) {
if (ws[wasm_ws_close_received]) {
const receive_status_ptr = ws[wasm_ws_receive_status_ptr];
setI32(receive_status_ptr, 0); // count
setI32(<any>receive_status_ptr + 4, 2); // type:close
Expand Down
Loading