WebSocketServer put_packet() jank

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jgee_23_

So Im working on a WebSocketServer on godot 3.5 mono and I came accross some serious jank that I dont seem to fully understand.

I use the following code on the server side to send packets over to a client:

byte[] pck = Encoding.UTF8.GetBytes(data);
network.GetPeer(player_id).PutPacket(pck);

where network is a WebSocketServer and data is a string I want to send, in this case, it is “unused_success”. On the client side, I use the following code to get the string:

byte[] pck = network.GetPeer(1).GetPacket();
GD.Print(System.Text.Encoding.UTF8.GetString(pck));

the output of this is ��unused_succe. However, if I change the code on the server side to print anything like so:

byte[] pck = Encoding.UTF8.GetBytes(data);
GD.Print("a");
network.GetPeer(player_id).PutPacket(pck);

then the client recieves the correct string. My assumption is that, somehow, GD.Print(pck); changes/corrects the encoding of the string, but I don’t know why or how to do this without having to print the bytes since it slows the server down.

UPDATE: these are the packets received when printing (so correct packets):
117
110
117
115
101
100
95
115
117
99
99
101
115
115

these are the jank packets received by client when not printing on server side:
130
14
117
110
117
115
101
100
95
115
117
99
99
101

jgee_23_ | 2023-05-08 13:20

:bust_in_silhouette: Reply From: jgee_23_

Apparently this happens when calling PutPacket() via a System.Threading.Thread on the server’s side. To fix this, just don’t use PutPacket() in a thread :stuck_out_tongue:

What I did to avoid this is make a queue for any messages that need to be sent which are sent in Process(delta), so I can just add a message to the queue in the thread, instead of directly calling PutPacket().