NativeWebSocket
NativeWebSocket copied to clipboard
Connect() is not the same on WebGL as on other builds
I'm not sure if this is by design, or an issue, but on non-WebGL builds, await websocket.Connect()
will return when the socket is open (or failed, I suppose).
On WebGL however, as Connect()
returns Task.CompletedTask
immediately, this isn't the case, and if you have this in a "synchronous" context, the socket isn't actually available. You need to loop and wait until OnOpen
is called.
So this code:
await websocket.Connect();
await websocket.SendText("hello");
doesn't work on WebGL. You need to do something like:
await websocket.Connect();
// await wrapper around coroutine call with something like Unity3dAsyncAwaitUtil
await new WaitUntil( () => websocket.State == WebSocketState.Open );
await websocket.SendText("hello");
By sending your message in the OnOpen()
event, you can avoid this issue entirely.
websocket.OnOpen += () => { websocket.Send(System.Text.Encoding.UTF8.GetBytes("hello")); };
async websocket.Connect();