endel / NativeWebSocket

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

websocket.OnMessage not recieving communication from the server #65

Closed nirharpaz closed 2 years ago

nirharpaz commented 2 years ago

this is my code

` string WebSocketURI="uri" void Start() { InitilizeWebSocket(); } private async void InitilizeWebSocket() { websocket = new WebSocket(WebSocketURI);

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

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

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

    websocket.OnMessage += (bytes) =>
    {
        Debug.Log("new message");

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

    await websocket.Connect();

}`

I initialized the server. ReportStartGame generates a JSON which is then sent to the websocket, the communication is received successfully. I tested the output in https://www.piesocket.com/websocket-tester. In response to the Con up, I received a comm from server with a json I should not be handling (with HandleGameData).

However, websocket.OnMessage is never triggered. Its not that there is problem with the data, but the Debug.Log("new message"); is never invoked.

endel commented 2 years ago

hey, are you processing the messages like in this example?

https://github.com/endel/NativeWebSocket/blob/master/NativeWebSocket/Assets/Samples~/WebSocketExample/Connection.cs#L46-L51

nirharpaz commented 2 years ago

I did in fact it seems that when I started a fresh new script copy-paste it worked. However, I should now alter the issue to the following one: https://stackoverflow.com/questions/72292098/websocket-sending-fails-unless-i-use-invokerepeating

In short, InvokeRepeating works, Invoke doesn't, SendWebSocketMessage() doesn't, coroutine doesn't. can you advise how should I invoke it once in a way It will properly work?

nirharpaz commented 2 years ago

It seems to work now