NativeWebSocket icon indicating copy to clipboard operation
NativeWebSocket copied to clipboard

Connect() is not the same on WebGL as on other builds

Open divillysausages opened this issue 3 years ago • 1 comments

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");

divillysausages avatar Dec 04 '20 09:12 divillysausages

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();

zalo avatar Dec 08 '20 01:12 zalo