From b2a5aec0fbfb6843b5db802a84856eac23823e1e Mon Sep 17 00:00:00 2001
From: Bjoern Esswein <bjoern.esswein@gmail.com>
Date: Sat, 7 Oct 2023 20:59:02 +0200
Subject: [PATCH] read the whole websoket message in one async call

---
 Runtime/ChromeDevtools/BrowserTab.cs | 65 +++++++++++++++-------------
 1 file changed, 35 insertions(+), 30 deletions(-)

diff --git a/Runtime/ChromeDevtools/BrowserTab.cs b/Runtime/ChromeDevtools/BrowserTab.cs
index 9d85da6..2faf128 100644
--- a/Runtime/ChromeDevtools/BrowserTab.cs
+++ b/Runtime/ChromeDevtools/BrowserTab.cs
@@ -39,7 +39,7 @@ namespace ChromeDevTools
 
             // open remote devtools websocket connection
             /**
-             * Note: Forebg wl compatibility you need to use the JavaScript plugin, see also https://docs.unity3d.com/Manual/webgl-networking.html#UsingWebSockets
+             * Note: For webgl compatibility you need to use the JavaScript plugin, see also https://docs.unity3d.com/Manual/webgl-networking.html#UsingWebSockets
              */
             ws.ConnectAsync(new Uri(pageTarget.WebSocketDebuggerUrl), Browser.cancellationTokenSource.Token);
         }
@@ -116,41 +116,46 @@ namespace ChromeDevTools
             // start the message receive loop (it will exit when the coroutine is stopped)
             while (true)
             {
-                string msgString;
-
-                // create a MemoryStream to reconstruct the message
-                using (var ms = new MemoryStream())
+                async Task<string> read()
                 {
-                    WebSocketReceiveResult result;
-
-                    /* A part of the message will be read into the message buffer and than be transfered
-                     * to the MemoryStream. This will be repeated until the complete message has been received.
-                     */
-                    do
+                    // create a MemoryStream to reconstruct the message
+                    using (var ms = new MemoryStream())
                     {
-                        var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
-                        var reseiveTask = ws.ReceiveAsync(messageBuffer, Browser.cancellationTokenSource.Token);
+                        WebSocketReceiveResult result;
+
+                        /* A part of the message will be read into the message buffer and than be transfered
+                         * to the MemoryStream. This will be repeated until the complete message has been received.
+                         */
+                        do
+                        {
+                            var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
+                            result = await ws.ReceiveAsync(messageBuffer, Browser.cancellationTokenSource.Token);
+
+                            // write the messageBuffer to the MemoryStream
+                            ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
+                        } while (!result.EndOfMessage);
+
+
+                        // If the webSocket message type isn't text ignore this message
+                        if (!(result.MessageType == WebSocketMessageType.Text))
+                        {
+                            Debug.LogError($"Unexpected WebSocketMessageType: {result.MessageType}");
+                            return await read();
+                        }
+
+                        // convert the message stream to string
+                        return Encoding.UTF8.GetString(ms.ToArray());
+                    }
+                }
 
-                        // yield the coroutine until the async Task "reseiveTask" is completed
-                        yield return new WaitUntil(() => reseiveTask.IsCompleted);
-                        result = reseiveTask.Result;
 
-                        // write the messageBuffer to the MemoryStream
-                        ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
-                    }
-                    while (!result.EndOfMessage);
+                var readTask = read();
+                // yield the coroutine until the async Task "reseiveTask" is completed
+                yield return new WaitUntil(() => readTask.IsCompleted);
 
-                    // If the webSocket message type isn't text ignore this message
-                    if (!(result.MessageType == WebSocketMessageType.Text))
-                    {
-                        Debug.LogError($"Unexpected WebSocketMessageType: {result.MessageType}");
-                        continue;
-                    }
+                string msgString = readTask.Result;
 
-                    // convert the message stream to string
-                    msgString = Encoding.UTF8.GetString(ms.ToArray());
-                    Debug.Log($"ws reseived: '{msgString}'");
-                }
+                Debug.Log($"ws reseived: '{msgString}'");
 
                 // deserialize the devtools response wrapper
                 var response = JsonConvert.DeserializeObject<DevtoolsResponseWrapper>(msgString, Browser.serializerSettings);
-- 
GitLab