Network trouble: Read TCP/IP packets by client

Godot Version

latest

Question

Hello guys! I have a question about reading TCP/IP packets from server.
I have a java server which can give responses/requests to client, any packet structure is starts from header:

int32 > packet_length
int32 > packet_id

I more quilified in Java lang, so server doesnt have any problems with decoding/encoding the messages from/to godot client (Spring + Netty), but on client i have some trouble when the byte array stream is coming and we start read them and I wrote this code for slicing it to packets:

func slice_to_packets() -> Array[PackedByteArray]:
	var array: Array[PackedByteArray] = []
	var original_position: int = buffer.get_position()
	buffer.seek(0)
	
	var marker: int = 0
	while buffer.get_available_bytes() >= 8:
		# read lenght of next packet
		var packet_length: int = buffer.get_32()
		if packet_length < 4:
			break

		buffer.seek(marker)

		# check available bytes for fill packet
		if buffer.get_available_bytes() < packet_length - 4: # reduce length, we read them above
			Log.warn("Incomplete packet! Size = {1} bytes, but only {2} available.", [packet_length, buffer.get_available_bytes()])
			return []
		
		# read packet
		var packet_data: Array = buffer.get_data(packet_length)
		if packet_data[0] == OK:  # get_data return array struct as [error, data[]]
			array.append(packet_data[1])
			marker = packet_length
		else:
			push_error("Failed to read packet data")
			break
	
	# restore original position
	buffer.seek(original_position)
	return array

The problem is: when i send 2 packets from server (one after one), on the client I get summary bytes of them (it’s ok, cause stream) after that code above must read them and with income packet header’s help client to read all bytes for the first packet and second (divide them as two datas, deserialzie them and put to the array for further handle). And it’s works but sometimes client falls into this code block:

		if buffer.get_available_bytes() < packet_length - 4: # reduce length, we read them above
			Log.warn("Incomplete packet! Size = {1} bytes, but only {2} available.", [packet_length, buffer.get_available_bytes()])
			return []

In {2} i can see bytes which came and the value can be insane like 8128381238. I understand at something went wrong when reading was started, but not understand where i fuckup.

Code where i get server answers located in _process inside singleton class Network and maybe I must pout available bytes in some order of array? I’m Confused

I would appreciate any help with this matter, or any advise if you have experience reading packets from a server. Thank you very much for your attention!

Don’t think you’re allowed to seek on network sockets, but maybe Godot’s implementation is buffered; have you tried this code without using seek?