doing something dumb

This commit is contained in:
dingo
2026-01-17 20:42:02 -05:00
parent 583644fde6
commit 32fb57fa75
3 changed files with 137 additions and 105 deletions
+92 -76
View File
@@ -5,8 +5,11 @@ extends Node
## This script handles WebSocket connection to the game server and implements
## automatic ping/pong keepalive mechanism to prevent idle timeout disconnections.
##
## The server will send PING messages every 30 seconds (configurable server-side).
## This client automatically responds with PONG to reset the server's idle timeout.
## PROTOCOL: Uses server's JSON envelope format for ALL messages including PING/PONG:
## [4-byte length][JSON: {"OpCode": int, "Payload": byte_array}]
##
## The server will send PING messages (OpCode 2) every 30 seconds (configurable server-side).
## This client automatically responds with PONG (OpCode 3) to reset the server's idle timeout.
signal connected
signal disconnected
@@ -48,7 +51,6 @@ func _process(_delta):
# Receive and process all available packets
while socket.get_available_packet_count() > 0:
var packet = socket.get_packet()
print("[Network] Received packet, size: ", packet.size())
_handle_received_data(packet)
WebSocketPeer.STATE_CLOSING:
@@ -98,36 +100,45 @@ func disconnect_from_server():
socket.close()
print("[Network] Disconnecting from server...")
## Send a message to the server
## Send a message to the server using the server's expected JSON envelope format
## @param opcode: Message type identifier (see opcodes.gd)
## @param data: Dictionary of message data to send
func send_message(opcode: int, data: Dictionary = {}):
print("[Network] Send Message Called to send opCode: ", opcode)
if not _is_connected:
push_warning("[Network] Cannot send message - not connected")
return
# Serialize message to JSON
var json_string = JSON.stringify(data)
var payload = json_string.to_utf8_buffer()
# Serialize payload to JSON bytes
var payload_json = JSON.stringify(data)
var payload_bytes = payload_json.to_utf8_buffer()
# Create frame: [4 bytes length][1 byte opcode][payload]
var frame_length = 1 + payload.size()
var frame = PackedByteArray()
# Create message envelope matching server's expected format:
# {"OpCode": int, "Payload": [byte_array]}
var message = {
"OpCode": opcode,
"Payload": Array(payload_bytes) # Convert to array of ints
}
var message_json = JSON.stringify(message)
var message_bytes = message_json.to_utf8_buffer()
# Write length as big-endian 32-bit integer
frame.append((frame_length >> 24) & 0xFF)
frame.append((frame_length >> 16) & 0xFF)
frame.append((frame_length >> 8) & 0xFF)
frame.append(frame_length & 0xFF)
# Create framed message with 4-byte big-endian length prefix
var message_length = message_bytes.size()
var framed = PackedByteArray()
framed.resize(4 + message_length)
# Write opcode
frame.append(opcode)
# Write big-endian length prefix
framed[0] = (message_length >> 24) & 0xFF
framed[1] = (message_length >> 16) & 0xFF
framed[2] = (message_length >> 8) & 0xFF
framed[3] = message_length & 0xFF
# Write payload
frame.append_array(payload)
# Copy message bytes
for i in range(message_length):
framed[4 + i] = message_bytes[i]
# Send to server
var err = socket.send(frame)
var err = socket.send(framed)
if err != OK:
push_error("[Network] Failed to send message, error: ", err)
@@ -137,7 +148,7 @@ func _handle_received_data(packet: PackedByteArray):
_receive_buffer.append_array(packet)
# Process all complete messages in buffer
while _receive_buffer.size() >= 5: # Minimum: 4 bytes length + 1 byte opcode
while _receive_buffer.size() >= 4:
# Read length (big-endian 32-bit integer)
var message_length = (
(_receive_buffer[0] << 24) |
@@ -147,7 +158,7 @@ func _handle_received_data(packet: PackedByteArray):
)
# Validate message length
if message_length < 1 or message_length > 4 * 1024 * 1024:
if message_length <= 0 or message_length > 4 * 1024 * 1024:
push_error("[Network] Invalid message length: ", message_length)
_receive_buffer.clear()
disconnect_from_server()
@@ -159,49 +170,64 @@ func _handle_received_data(packet: PackedByteArray):
# Incomplete message, wait for more data
break
# Extract opcode
var opcode = _receive_buffer[4]
# Extract payload (if any)
var payload_size = message_length - 1
var payload_bytes = PackedByteArray()
if payload_size > 0:
payload_bytes = _receive_buffer.slice(5, 5 + payload_size)
# Extract message bytes (skip the 4-byte length prefix)
var message_bytes = _receive_buffer.slice(4, 4 + message_length)
# Remove processed message from buffer
_receive_buffer = _receive_buffer.slice(total_frame_size)
_receive_buffer = _receive_buffer.slice(4 + message_length)
# Handle the message
_handle_message(opcode, payload_bytes)
# Parse JSON envelope: {"OpCode": int, "Payload": byte_array}
var message_text = message_bytes.get_string_from_utf8()
var json = JSON.new()
var parse_result = json.parse(message_text)
if parse_result != OK:
push_error("[Network] Failed to parse message JSON: " + json.get_error_message())
push_error("[Network] Raw message (first 200 chars): " + message_text.substr(0, 200))
continue
var message = json.data
var opcode: int = message.get("opCode", message.get("OpCode", 0))
# Decode payload
var payload_data = message.get("payload", message.get("Payload", null))
var decoded_data = {}
if payload_data != null:
var payload_string: String
if payload_data is String:
# Base64 encoded payload
payload_string = Marshalls.base64_to_utf8(payload_data)
elif payload_data is Array:
# Array of bytes (this is the common case)
var byte_array = PackedByteArray(payload_data)
payload_string = byte_array.get_string_from_utf8()
else:
# Other type, stringify it
payload_string = JSON.stringify(payload_data)
# Parse payload JSON
var payload_json = JSON.new()
if payload_json.parse(payload_string) == OK:
decoded_data = payload_json.data
else:
decoded_data = {"raw": payload_string}
# Handle message
_handle_message(opcode, decoded_data)
## Process a single decoded message
func _handle_message(opcode: int, payload: PackedByteArray):
func _handle_message(opcode: int, data: Dictionary):
# Handle ping/pong messages internally (don't emit to game logic)
match opcode:
2: # PING from server
_handle_ping_message()
return
3: # PONG from server (shouldn't happen, but handle gracefully)
print("[Network] Unexpected PONG received from server")
return
if opcode == 2: # PING from server
_handle_ping_message()
return
elif opcode == 3: # PONG from server (shouldn't happen, but handle gracefully)
print("[Network] Unexpected PONG received from server")
return
# For all other messages, parse JSON payload and emit to game
var data = {}
if payload.size() > 0:
var json_string = payload.get_string_from_utf8()
var json = JSON.new()
var parse_result = json.parse(json_string)
if parse_result == OK:
data = json.data
else:
push_warning("[Network] Failed to parse JSON for opcode ", opcode)
print("[Network] JSON parse error: ", json.get_error_message())
print("[Network] Invalid JSON: ", json_string)
# Emit message to game logic
# Emit all other messages to game logic
message_received.emit(opcode, data)
## Handle PING message from server - respond with PONG
@@ -211,25 +237,15 @@ func _handle_ping_message():
print("[Network] PING received (count: %d), sending PONG..." % _ping_count)
# Send PONG response (OpCode 3, empty payload)
var pong_frame = PackedByteArray()
# Send PONG using standard message format (OpCode 3, empty payload)
send_message(3, {})
# Length: 1 byte (just the opcode)
pong_frame.append(0) # High bytes of length
pong_frame.append(0)
pong_frame.append(0)
pong_frame.append(1) # Low byte of length = 1
# OpCode: 3 (PONG)
pong_frame.append(3)
# Send directly without going through send_message to avoid JSON overhead
var err = socket.send(pong_frame)
if err == OK:
_pong_sent_count += 1
print("[Network] PONG sent successfully (count: %d)" % _pong_sent_count)
else:
push_error("[Network] Failed to send PONG, error: ", err)
_pong_sent_count += 1
print("[Network] PONG sent successfully (count: %d)" % _pong_sent_count)
## Check if the socket is currently connected
func is_socket_connected() -> bool:
return _is_connected and socket.get_ready_state() == WebSocketPeer.STATE_OPEN
## Get connection statistics for debugging
func get_connection_stats() -> Dictionary: