mikerochip / unity-websocket

Easy-to-use WebSocket MonoBehaviour for Unity. NativeWebSocket alternative.
Other
36 stars 5 forks source link

Unity freezes when trying to open multiple unity-websockets (i.e. 100 connections) #15

Closed stefanbursuc closed 3 weeks ago

stefanbursuc commented 1 month ago

When I tried to open multiple connections to a server to stress tests some scenarios, Unity freezes and needs to be killed and restart to recover it.

mikerochip commented 1 month ago

Can you elaborate on what results you're seeing? As in, does it slowdown as you approach a higher number of instances or does it just immediately freeze at a certain number? Also, does your PR make Unity appear to operate normally? Is it still slow, but usable? etc.

stefanbursuc commented 1 month ago

I have added a small Unity Project that reproduces the issue. It tries to make 30 connections to wss://echo.websocket.org

I am not very proficient in programming with async/await. I just found out where the hang occurs by commenting/uncommenting various pieces of the code.

UnityWebSocketHangTest.zip

stefanbursuc commented 1 month ago

This is the code that creates the connections:

    private IEnumerator StartTestCoroutine()
    {
        for (int i = 1; i <= 30; i++)
        {
            StartConnection();
            yield return new WaitForSeconds(0.05f);
        }
    }

    private void StartConnection()
    {
        WebSocketConnection connectiuon = Instantiate(connectionPrefab);
        connectiuon.Connect(url);
        connectiuon.StateChanged += OnStateChanged;
    }
mikerochip commented 3 weeks ago

@stefanbursuc After some testing, re-worked the code to not continue in the lock and to have a await Task.Yield(); if no outgoing messages were detected. This felt more consistent than an arbitrary delay since it follows the pattern used in the various async Tasks in the WebSocketConnection class itself, i.e. I think you found an oversight, and I'm grateful for that. Give the latest a try and LMK?