TCP packets come in chunks, not seperated

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wombatTurkey
:warning: Old Version Published before Godot 3 was released.

Example to connect:

func connectToServer(ip, port):
	client = StreamPeerTCP.new()
	client.connect(ip, port)  

Then in my update, I use: (this might be where my problem is)

if client.is_connected() && client.get_available_bytes() >0:
    print(str(client.get_string(client.get_available_bytes())))

Now, I’m running a basic TCP Server in nodejs. If I do:

socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')
socket.write('PATCH 1.10')

It actually doesn’t send as individual messages, so when I get my string from get_string (above) I receive:

Is there a way to make it so each time a message (packet) is sent, they come as individual packets instead of added to the TCP Stream? Thanks for reading!

Sorry folks, looks like this is just how TCP Works (Stream Based)

java - NodeJS TCP Server, onData small chunks - Stack Overflow

I don’t think it’s Godot’s fault. I’m just used to my WebSocket server :frowning:

More info here: networking - TCP stream vs UDP message - Stack Overflow

wombatTurkey | 2016-07-28 02:38

:bust_in_silhouette: Reply From: Bojidar Marinov

This is part of the way TCP works – it is stream-based, not packet-based, unlike UDP.

The simplest way to do what would want, though, would be to pick some “message delimiter character”, like \n or even \0, and then append all bytes into an array until you meet it. Then you would process the next message.

A more involved way to solve it would be to encode all messages as JSON, and then (somehow) monitor when the JSON structure ends, and the next begins.

@Boljidar, I did the \n delimited approach, works awesome! Thank you!

wombatTurkey | 2016-07-29 17:54