endel / NativeWebSocket

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)
Other
1.13k stars 155 forks source link

Cannot reconnect a WebSocket in WebGL #18

Open fnunnari opened 3 years ago

fnunnari commented 3 years ago

The sequence...

Everything works fine. All the calls are performed inside the Update() method. The three calls are user-controlled. Hence, some seconds pass between them.

Now, trying to re-open the socket again with: Invoke() on a method calling await _webSock.Connect(); Work good in Unity Editor. Fails in WebGL with error:

WebSocketInvalidStateException: WebSocket is already connected or in connecting state.
  at NativeWebSocket.WebSocket.Connect () [0x00000] in <00000000000000000000000000000000>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <00000000000000000000000000000000>:0 

(Filename: currently not available on il2cpp Line: -1)
jsharf commented 2 years ago

I was able to work around this by discarding the disconnected object and creating a new websocket.

_webSocket = new WebSocket(_url);

Just make sure that before you do that, you unsubscribe from the handlers for the previous WebSocket object, or you've got yourself a memory leak. I do that with this OnClose handler:

    private void OnClose(WebSocketCloseCode code)
    {
        Debug.Log("Connection closed: " + code);
        _webSocket.OnOpen -= OnOpen;
        _webSocket.OnError -= OnError;
        _webSocket.OnClose -= OnClose;
        _webSocket.OnMessage -= OnMessage;
    }

    _webSocket.OnClose += OnClose;