endel / NativeWebSocket

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

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

Open divillysausages opened 3 years ago

divillysausages commented 3 years ago

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");
zalo commented 3 years ago

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