NativeWebSocket
NativeWebSocket copied to clipboard
Cannot reconnect a WebSocket in WebGL
The sequence...
- Opening a socket: Invoke() on a method calling
await _webSock.Connect(); - Sending messages: Calling
_webSock.SendText(msg); - Closing the socket: Invoke() on a method calling
await _webSock.Close();
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)
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;