'WebSocket sending fails unless I use InvokeRepeating

I've implemented a socket connection module according to the instructions here https://github.com/endel/NativeWebSocket

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using NativeWebSocket;

public class Connection : MonoBehaviour
{
    WebSocket websocket;
    public bool SpamSend;
    public float spamEvery = 3f;
    public string uri = "ws://localhost:2567";

    [TextArea] public string message;

    private string CurrectData;
    // Start is called before the first frame update
    async void Start()
    {
        CurrectData = message;
        websocket = new WebSocket(uri);

        InitilizeWebSocket();
    }

    async void InitilizeWebSocket()
    {
        websocket.OnOpen += () =>
        {
            Debug.Log("Connection open!");
        };

        websocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
        };

        websocket.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");
        };

        websocket.OnMessage += (bytes) =>
        {
            Debug.Log("OnMessage!");
            //Debug.Log(bytes);

            // getting the message as a string
            var message = System.Text.Encoding.UTF8.GetString(bytes);
            Debug.Log("OnMessage! " + message);
        };

        if(SpamSend)
            // Keep sending messages at every 0.3s
            InvokeRepeating("SendWebSocketMessage", 0.0f, spamEvery);

        // waiting for messages
        await websocket.Connect();
    }


    void Update()
    {
    #if !UNITY_WEBGL || UNITY_EDITOR
        websocket.DispatchMessageQueue();
    #endif
    }

    async void SendWebSocketMessage()
    {
        if (websocket.State == WebSocketState.Open)
        {
            // Sending bytes
       //     await websocket.Send(new byte[] { 10, 20, 30 });

            // Sending plain text
            await websocket.SendText(CurrectData);
            CancelInvoke("SendWebSocketMessage");
        }
    }

    private async void OnApplicationQuit()
    {
        await websocket.Close();
    }
}

you may now notice the oddity of "invokeRepeating" and CancelInvoke. this is where I've encountered a problem.

when I tried to just Invoke, I received no response from the server as if it was never sent. nor when I tried a coroutine - with or without waitForSeconds. nor when I simply tried SendWebSocketMessage().

What did I miss that only the invokeRepeating made it through?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source