259 lines
8.2 KiB
GDScript
259 lines
8.2 KiB
GDScript
extends Node
|
|
|
|
## Network Connection Manager with Ping/Pong Keepalive Support
|
|
##
|
|
## This script handles WebSocket connection to the game server and implements
|
|
## automatic ping/pong keepalive mechanism to prevent idle timeout disconnections.
|
|
##
|
|
## 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
|
|
signal message_received(opcode: int, data: Dictionary)
|
|
signal connection_error(error: String)
|
|
|
|
const SERVER_URL = "wss://srs.aeternalisgames.com/ws"
|
|
|
|
# WebSocket connection instance
|
|
var socket: WebSocketPeer = WebSocketPeer.new()
|
|
|
|
# Buffer for handling fragmented messages
|
|
var _receive_buffer: PackedByteArray = PackedByteArray()
|
|
|
|
# Connection state tracking
|
|
var _is_connected: bool = false
|
|
|
|
# Statistics for monitoring connection health
|
|
var _last_ping_received_time: float = 0.0
|
|
var _ping_count: int = 0
|
|
var _pong_sent_count: int = 0
|
|
|
|
func _ready():
|
|
set_process(false)
|
|
|
|
## Main processing loop - polls WebSocket and handles incoming messages
|
|
func _process(_delta):
|
|
socket.poll()
|
|
|
|
var state = socket.get_ready_state()
|
|
|
|
match state:
|
|
WebSocketPeer.STATE_OPEN:
|
|
if not _is_connected:
|
|
_is_connected = true
|
|
print("[Network] WebSocket connected successfully")
|
|
connected.emit()
|
|
|
|
# Receive and process all available packets
|
|
while socket.get_available_packet_count() > 0:
|
|
var packet = socket.get_packet()
|
|
_handle_received_data(packet)
|
|
|
|
WebSocketPeer.STATE_CLOSING:
|
|
print("[Network] WebSocket closing...")
|
|
|
|
WebSocketPeer.STATE_CLOSED:
|
|
var close_code = socket.get_close_code()
|
|
var close_reason = socket.get_close_reason()
|
|
print("[Network] WebSocket closed - code: %d, reason: %s" % [close_code, close_reason])
|
|
|
|
if _is_connected:
|
|
_is_connected = false
|
|
disconnected.emit()
|
|
|
|
set_process(false)
|
|
|
|
## Establish connection to game server
|
|
func connect_to_server() -> Error:
|
|
_receive_buffer.clear()
|
|
_ping_count = 0
|
|
_pong_sent_count = 0
|
|
_last_ping_received_time = 0.0
|
|
|
|
# Reset socket for fresh connection
|
|
socket = WebSocketPeer.new()
|
|
|
|
# Increase buffer sizes for large dungeon data transfers
|
|
socket.inbound_buffer_size = 8 * 1024 * 1024 # 8MB for large state updates
|
|
socket.outbound_buffer_size = 1024 * 1024 # 1MB for outgoing messages
|
|
socket.max_queued_packets = 4096 # Handle burst traffic
|
|
|
|
print("[Network] Attempting connection to: ", SERVER_URL)
|
|
var err = socket.connect_to_url(SERVER_URL)
|
|
|
|
if err == OK:
|
|
set_process(true)
|
|
print("[Network] Connection initiated, waiting for handshake...")
|
|
else:
|
|
print("[Network] Connection failed with error: ", err)
|
|
connection_error.emit("Failed to initiate connection: " + str(err))
|
|
|
|
return err
|
|
|
|
## Gracefully disconnect from server
|
|
func disconnect_from_server():
|
|
if _is_connected:
|
|
socket.close()
|
|
print("[Network] Disconnecting from 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 payload to JSON bytes
|
|
var payload_json = JSON.stringify(data)
|
|
var payload_bytes = payload_json.to_utf8_buffer()
|
|
|
|
# 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()
|
|
|
|
# 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 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
|
|
|
|
# Copy message bytes
|
|
for i in range(message_length):
|
|
framed[4 + i] = message_bytes[i]
|
|
|
|
# Send to server
|
|
var err = socket.send(framed)
|
|
if err != OK:
|
|
push_error("[Network] Failed to send message, error: ", err)
|
|
|
|
## Handle incoming data packets from server
|
|
func _handle_received_data(packet: PackedByteArray):
|
|
# Add to buffer
|
|
_receive_buffer.append_array(packet)
|
|
|
|
# Process all complete messages in buffer
|
|
while _receive_buffer.size() >= 4:
|
|
# Read length (big-endian 32-bit integer)
|
|
var message_length = (
|
|
(_receive_buffer[0] << 24) |
|
|
(_receive_buffer[1] << 16) |
|
|
(_receive_buffer[2] << 8) |
|
|
_receive_buffer[3]
|
|
)
|
|
|
|
# Validate message length
|
|
if message_length <= 0 or message_length > 4 * 1024 * 1024:
|
|
push_error("[Network] Invalid message length: ", message_length)
|
|
_receive_buffer.clear()
|
|
disconnect_from_server()
|
|
return
|
|
|
|
# Check if we have the complete message
|
|
var total_frame_size = 4 + message_length
|
|
if _receive_buffer.size() < total_frame_size:
|
|
# Incomplete message, wait for more data
|
|
break
|
|
|
|
# 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(4 + message_length)
|
|
|
|
# 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))
|
|
#print("[Network] OpCode Recieved: ", opcode)
|
|
# 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, data: Dictionary):
|
|
# Handle ping/pong messages internally (don't emit to game logic)
|
|
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
|
|
|
|
# Emit all other messages to game logic
|
|
message_received.emit(opcode, data)
|
|
|
|
## Handle PING message from server - respond with PONG
|
|
func _handle_ping_message():
|
|
_ping_count += 1
|
|
_last_ping_received_time = Time.get_ticks_msec() / 1000.0
|
|
|
|
print("[Network] PING received (count: %d), sending PONG..." % _ping_count)
|
|
|
|
# Send PONG using standard message format (OpCode 3, empty payload)
|
|
send_message(3, {})
|
|
|
|
_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:
|
|
return {
|
|
"is_connected": _is_connected,
|
|
"ping_count": _ping_count,
|
|
"pong_sent_count": _pong_sent_count,
|
|
"last_ping_seconds_ago": (Time.get_ticks_msec() / 1000.0) - _last_ping_received_time if _last_ping_received_time > 0 else -1,
|
|
"socket_state": socket.get_ready_state()
|
|
}
|