From ee3539e42cccded1c3a6a0489d6c86ab66ac8392 Mon Sep 17 00:00:00 2001 From: Ru Cindrea Date: Fri, 13 Nov 2026 08:52:58 +0200 Subject: [PATCH 1/2] fix: Close() no longer waits the full close timeout The close sequence saves receivingExitedEvent, clears the field via ReleaseCommonResources(false), then waits on the saved event in CloseHandshake. The receive loop signalled the field, which was already null, so the waiting Close() was never woken and always waited out waitTime (5 s on the client). The receive loop now signals the event it was started with. A late Set after the close sequence has given up and disposed the event is ignored. Adds tools/CloseTiming, a console harness that times a client Close() against a System.Net server that answers the close frame, and a server-side session close. Before: ~5,005 ms, WasClean=False. After: 0-3 ms, WasClean=True. --- tools/CloseTiming/CloseTiming.csproj | 14 ++ tools/CloseTiming/Program.cs | 132 +++++++++++++++++++ websocket-sharp/websocket-sharp/WebSocket.cs | 21 ++- 3 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tools/CloseTiming/CloseTiming.csproj create mode 100644 tools/CloseTiming/Program.cs diff --git a/tools/CloseTiming/CloseTiming.csproj b/tools/CloseTiming/CloseTiming.csproj new file mode 100644 index 000000000..429f715fe --- /dev/null +++ b/tools/CloseTiming/CloseTiming.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + disable + enable + + + + + + + diff --git a/tools/CloseTiming/Program.cs b/tools/CloseTiming/Program.cs new file mode 100644 index 000000000..d27c2f7e9 --- /dev/null +++ b/tools/CloseTiming/Program.cs @@ -0,0 +1,132 @@ +// Measures how long AltWebSocketSharp takes to close a connection when the +// peer answers the close frame promptly. A healthy close takes a few ms; the +// bug this harness was written for made every close wait the full 5 s timeout. +// +// Usage: dotnet run -c Release --project tools/CloseTiming [iterations] +// Exit code 1 if any close takes 1 s or longer. + +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using AltWebSocketSharp; +using AltWebSocketSharp.Server; +using NetClientWebSocket = System.Net.WebSockets.ClientWebSocket; +using NetWebSocketCloseStatus = System.Net.WebSockets.WebSocketCloseStatus; +using NetWebSocketMessageType = System.Net.WebSockets.WebSocketMessageType; + +static class Program +{ + const long LimitMs = 1000; + + static int Main(string[] args) + { + var iterations = args.Length > 0 ? int.Parse(args[0]) : 3; + var failed = false; + + for (var i = 1; i <= iterations; i++) + { + var (clientMs, clean) = ClientCloseAgainstSystemNetServer(); + var serverMs = ServerCloseAgainstSystemNetClient(); + Console.WriteLine($"run {i}: ClientWebSocket.Close() = {clientMs} ms (WasClean={clean}), server-side session close = {serverMs} ms"); + failed |= clientMs >= LimitMs || serverMs >= LimitMs || !clean; + } + + Console.WriteLine(failed ? "FAIL: a close took >= 1000 ms or the client close was not clean" : "OK: every close took < 1000 ms and the client close was clean"); + return failed ? 1 : 0; + } + + static int FreePort() + { + var l = new TcpListener(IPAddress.Loopback, 0); + l.Start(); + var port = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + return port; + } + + // AltWebSocketSharp.ClientWebSocket closes against a System.Net.WebSockets + // server that echoes the close frame as soon as it receives it. + static (long ms, bool wasClean) ClientCloseAgainstSystemNetServer() + { + var port = FreePort(); + var prefix = $"http://127.0.0.1:{port}/"; + using var listener = new HttpListener(); + listener.Prefixes.Add(prefix); + listener.Start(); + + var serverTask = Task.Run(async () => + { + var ctx = await listener.GetContextAsync(); + var wsCtx = await ctx.AcceptWebSocketAsync(null); + var ws = wsCtx.WebSocket; + var buffer = new byte[1024]; + while (true) + { + var result = await ws.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + if (result.MessageType == NetWebSocketMessageType.Close) + { + await ws.CloseOutputAsync(NetWebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + break; + } + } + }); + + var client = new ClientWebSocket($"ws://127.0.0.1:{port}/"); + client.Log.Level = LogLevel.Fatal; + var wasClean = false; + client.OnClose += (_, e) => wasClean = e.WasClean; + client.Connect(); + if (client.ReadyState != WebSocketState.Open) + throw new Exception("client did not connect"); + + var sw = Stopwatch.StartNew(); + client.Close(); + sw.Stop(); + + try { serverTask.Wait(TimeSpan.FromSeconds(10)); } catch (AggregateException) { } + listener.Stop(); + return (sw.ElapsedMilliseconds, wasClean); + } + + class Holder : WebSocketBehavior + { + public static TaskCompletionSource Opened; + public void CloseFromServer() => Sessions.CloseSession(ID); + protected override void OnOpen() => Opened.TrySetResult(this); + } + + // AltWebSocketSharp.Server closes a session against a System.Net.WebSockets + // client that answers the close frame as soon as it receives it. + static long ServerCloseAgainstSystemNetClient() + { + var port = FreePort(); + var server = new WebSocketServer($"ws://127.0.0.1:{port}"); + server.Log.Level = LogLevel.Fatal; + Holder.Opened = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + server.AddWebSocketService("/"); + server.Start(); + + using var client = new NetClientWebSocket(); + client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/"), CancellationToken.None).Wait(); + var clientTask = Task.Run(async () => + { + var buffer = new byte[1024]; + while (client.State == System.Net.WebSockets.WebSocketState.Open) + { + var result = await client.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + if (result.MessageType == NetWebSocketMessageType.Close) + break; // System.Net answers the close frame automatically + } + }); + + var holder = Holder.Opened.Task.Result; + var sw = Stopwatch.StartNew(); + holder.CloseFromServer(); + sw.Stop(); + + // The server drops TCP after its close handshake; an EOF here is fine. + try { clientTask.Wait(TimeSpan.FromSeconds(10)); } catch (AggregateException) { } + server.Stop(); + return sw.ElapsedMilliseconds; + } +} diff --git a/websocket-sharp/websocket-sharp/WebSocket.cs b/websocket-sharp/websocket-sharp/WebSocket.cs index 66ade5727..c56195126 100644 --- a/websocket-sharp/websocket-sharp/WebSocket.cs +++ b/websocket-sharp/websocket-sharp/WebSocket.cs @@ -1224,11 +1224,16 @@ private void startReceiving() pongReceivedEvent = new ManualResetEvent(false); receivingExitedEvent = new ManualResetEvent(false); - ReceiveLoop(); + ReceiveLoop(receivingExitedEvent); } - private void ReceiveLoop() + // The loop signals the event it was started with, not the + // receivingExitedEvent field. The close sequence clears that field + // (ReleaseCommonResources) before it waits on the saved event in + // CloseHandshake, so signalling the field would never wake the + // waiting Close() and every close would wait out its full timeout. + private void ReceiveLoop(ManualResetEvent receivingExited) { void OnReadCompleted(WebSocketFrame frame) { @@ -1239,12 +1244,20 @@ void OnReadCompleted(WebSocketFrame frame) { logger.Info($"ReceiveLoop exit closed={closed} receivedFrameResult={receivedFrameResult}"); - receivingExitedEvent?.Set(); + try + { + receivingExited?.Set(); + } + catch (ObjectDisposedException) + { + // The close sequence already gave up waiting and disposed it. + } + return; } // Receive next asap because the Ping or Close needs a response to it. - ReceiveLoop(); + ReceiveLoop(receivingExited); if (inMessage || !HasMessage || readyState != WebSocketState.Open) return; From 4bdb5320c5892264c879ac76cbcae1b550e0c3c2 Mon Sep 17 00:00:00 2001 From: Ru Cindrea Date: Fri, 13 Nov 2026 09:30:47 +0200 Subject: [PATCH 2/2] fix: only a close frame wakes a waiting Close() Review feedback on the first fix: the receive loop signalled the receivingExited event whenever the state was Closed. A data frame still in flight during a local close therefore woke CloseHandshake, which reported WasClean = true without the peer's close reply. The loop now keeps its own stream reference and, while a local close is in progress, discards frames until a close frame arrives. A read failure after the close sequence has closed the stream is logged at Debug instead of being reported as a fatal error. CloseTiming now answers server close frames itself (System.Net's ReceiveAsync does not) and adds a case where the server sends a data frame and replies to the close 300 ms later. The previous commit returned in 0 ms with WasClean = true; this one waits about 300 ms for the real reply. --- tools/CloseTiming/Program.cs | 27 ++++++-- websocket-sharp/websocket-sharp/WebSocket.cs | 73 ++++++++++++++------ 2 files changed, 73 insertions(+), 27 deletions(-) diff --git a/tools/CloseTiming/Program.cs b/tools/CloseTiming/Program.cs index d27c2f7e9..432995c5e 100644 --- a/tools/CloseTiming/Program.cs +++ b/tools/CloseTiming/Program.cs @@ -17,6 +17,7 @@ static class Program { const long LimitMs = 1000; + const int InFlightDelayMs = 300; static int Main(string[] args) { @@ -25,13 +26,16 @@ static int Main(string[] args) for (var i = 1; i <= iterations; i++) { - var (clientMs, clean) = ClientCloseAgainstSystemNetServer(); + var (clientMs, clean) = ClientCloseAgainstSystemNetServer(0); + var (inFlightMs, inFlightClean) = ClientCloseAgainstSystemNetServer(InFlightDelayMs); var serverMs = ServerCloseAgainstSystemNetClient(); - Console.WriteLine($"run {i}: ClientWebSocket.Close() = {clientMs} ms (WasClean={clean}), server-side session close = {serverMs} ms"); + Console.WriteLine($"run {i}: ClientWebSocket.Close() = {clientMs} ms (WasClean={clean}), server-side session close = {serverMs} ms, Close() with a data frame before a {InFlightDelayMs} ms-late close reply = {inFlightMs} ms (WasClean={inFlightClean})"); failed |= clientMs >= LimitMs || serverMs >= LimitMs || !clean; + // Close() must wait for the real close reply, not return on the data frame. + failed |= inFlightMs < InFlightDelayMs - 50 || inFlightMs >= LimitMs || !inFlightClean; } - Console.WriteLine(failed ? "FAIL: a close took >= 1000 ms or the client close was not clean" : "OK: every close took < 1000 ms and the client close was clean"); + Console.WriteLine(failed ? "FAIL: see the timings above" : "OK: every close took < 1000 ms, client closes were clean, and Close() waited for the real close reply"); return failed ? 1 : 0; } @@ -45,8 +49,9 @@ static int FreePort() } // AltWebSocketSharp.ClientWebSocket closes against a System.Net.WebSockets - // server that echoes the close frame as soon as it receives it. - static (long ms, bool wasClean) ClientCloseAgainstSystemNetServer() + // server that echoes the close frame. With replyDelayMs > 0 the server + // first sends a data frame and only replies to the close after that delay. + static (long ms, bool wasClean) ClientCloseAgainstSystemNetServer(int replyDelayMs) { var port = FreePort(); var prefix = $"http://127.0.0.1:{port}/"; @@ -65,6 +70,12 @@ static int FreePort() var result = await ws.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); if (result.MessageType == NetWebSocketMessageType.Close) { + if (replyDelayMs > 0) + { + var data = System.Text.Encoding.UTF8.GetBytes("in flight"); + await ws.SendAsync(new ArraySegment(data), NetWebSocketMessageType.Text, true, CancellationToken.None); + await Task.Delay(replyDelayMs); + } await ws.CloseOutputAsync(NetWebSocketCloseStatus.NormalClosure, "", CancellationToken.None); break; } @@ -115,7 +126,11 @@ static long ServerCloseAgainstSystemNetClient() { var result = await client.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); if (result.MessageType == NetWebSocketMessageType.Close) - break; // System.Net answers the close frame automatically + { + // ReceiveAsync does not answer a close frame; send the reply. + await client.CloseOutputAsync(NetWebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + break; + } } }); diff --git a/websocket-sharp/websocket-sharp/WebSocket.cs b/websocket-sharp/websocket-sharp/WebSocket.cs index c56195126..a816d13aa 100644 --- a/websocket-sharp/websocket-sharp/WebSocket.cs +++ b/websocket-sharp/websocket-sharp/WebSocket.cs @@ -1224,40 +1224,63 @@ private void startReceiving() pongReceivedEvent = new ManualResetEvent(false); receivingExitedEvent = new ManualResetEvent(false); - ReceiveLoop(receivingExitedEvent); + ReceiveLoop(socketStream, receivingExitedEvent); } - // The loop signals the event it was started with, not the - // receivingExitedEvent field. The close sequence clears that field - // (ReleaseCommonResources) before it waits on the saved event in - // CloseHandshake, so signalling the field would never wake the - // waiting Close() and every close would wait out its full timeout. - private void ReceiveLoop(ManualResetEvent receivingExited) + // The loop keeps its own references to the stream and to the + // receivingExited event. The close sequence clears both fields + // (ReleaseClientResources / ReleaseServerResources and + // ReleaseCommonResources) before CloseHandshake waits on the saved + // event. Signalling the field would never wake the waiting Close(), + // and every close would wait out its full timeout. + // + // The loop signals the event only when a close frame arrives (or + // when processing a frame ends the connection), so a data frame + // that is still in flight during a local close is not mistaken for + // the peer's close reply. + private void ReceiveLoop(Stream stream, ManualResetEvent receivingExited) { - void OnReadCompleted(WebSocketFrame frame) + void SignalReceivingExited() { - var receivedFrameResult = ProcessReceivedFrame(frame); - var closed = readyState == WebSocketState.Closed; - - if (!receivedFrameResult || closed) + try { - logger.Info($"ReceiveLoop exit closed={closed} receivedFrameResult={receivedFrameResult}"); + receivingExited?.Set(); + } + catch (ObjectDisposedException) + { + // The close sequence already gave up waiting and disposed it. + } + } - try - { - receivingExited?.Set(); - } - catch (ObjectDisposedException) + void OnReadCompleted(WebSocketFrame frame) + { + if (readyState == WebSocketState.Closed) + { + // A local close is waiting for the peer's close reply. + // Ignore anything else that was already in flight. + if (frame.IsClose) { - // The close sequence already gave up waiting and disposed it. + logger.Info("ReceiveLoop exit: close reply received after the local close."); + SignalReceivingExited(); + return; } + ReceiveLoop(stream, receivingExited); + return; + } + + var receivedFrameResult = ProcessReceivedFrame(frame); + + if (!receivedFrameResult) + { + logger.Info("ReceiveLoop exit: the received frame ended the connection."); + SignalReceivingExited(); return; } // Receive next asap because the Ping or Close needs a response to it. - ReceiveLoop(receivingExited); + ReceiveLoop(stream, receivingExited); if (inMessage || !HasMessage || readyState != WebSocketState.Open) return; @@ -1267,11 +1290,19 @@ void OnReadCompleted(WebSocketFrame frame) void OnReadFailed(Exception ex) { + if (readyState == WebSocketState.Closed) + { + // The close sequence closed the stream (after the handshake + // or its timeout). Nothing is left to report. + logger.Debug("ReceiveLoop exit: the stream was closed after the local close."); + return; + } + logger.Fatal(ex.ToString()); Fatal("An exception has occurred while receiving.", ex); } - WebSocketFrame.ReadFrameAsync(socketStream, false, OnReadCompleted, OnReadFailed); + WebSocketFrame.ReadFrameAsync(stream, false, OnReadCompleted, OnReadFailed); }