mikerochip/unity-websocket

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

Closed this issue · 4 comments

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.

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.

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

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;
    }

@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?