85 lines
2.3 KiB
GDScript3
85 lines
2.3 KiB
GDScript3
|
extends Node
|
||
|
|
||
|
signal connected(s:StreamPeerTCP)
|
||
|
signal data(data:Array)
|
||
|
signal disconnected
|
||
|
signal error
|
||
|
|
||
|
@onready var _stream: StreamPeerTCP = StreamPeerTCP.new()
|
||
|
|
||
|
var _status: StreamPeerTCP.Status = StreamPeerTCP.STATUS_NONE
|
||
|
|
||
|
func _ready() -> void:
|
||
|
_status = _stream.get_status()
|
||
|
self.connect_to_host("127.0.0.1",3883)
|
||
|
|
||
|
func _process(delta: float) -> void:
|
||
|
_stream.poll()
|
||
|
var new_status = _stream.get_status()
|
||
|
if new_status != _status:
|
||
|
_status = new_status
|
||
|
match _status:
|
||
|
_stream.STATUS_NONE:
|
||
|
print("Disconnected from host.")
|
||
|
emit_signal("disconnected")
|
||
|
_stream.STATUS_CONNECTING:
|
||
|
print("Connecting.")
|
||
|
_stream.STATUS_CONNECTED:
|
||
|
print("Connected.")
|
||
|
emit_signal("connected",_stream.poll()
|
||
|
)
|
||
|
_stream.STATUS_ERROR:
|
||
|
print("Error with socket stream.")
|
||
|
emit_signal("error")
|
||
|
|
||
|
if _status == _stream.STATUS_CONNECTED:
|
||
|
if Input.is_action_just_pressed("ui_accept"):
|
||
|
print("Sending ...")
|
||
|
self.send("vrpn".to_ascii_buffer())
|
||
|
|
||
|
var available_bytes: int = _stream.get_available_bytes()
|
||
|
if available_bytes > 0:
|
||
|
print("available bytes: ", available_bytes)
|
||
|
var data: Array = _stream.get_partial_data(available_bytes)
|
||
|
# Check for read error.
|
||
|
if data[0] != OK:
|
||
|
print("Error getting data from stream: ", data[0])
|
||
|
emit_signal("error")
|
||
|
else:
|
||
|
emit_signal("data", data[1])
|
||
|
|
||
|
func connect_to_host(host: String, port: int) -> void:
|
||
|
print("Connecting to %s:%d" % [host, port])
|
||
|
# Reset status so we can tell if it changes to error again.
|
||
|
_status = _stream.STATUS_NONE
|
||
|
if _stream.connect_to_host(host, port) != OK:
|
||
|
print("Error connecting to host.")
|
||
|
emit_signal("error")
|
||
|
|
||
|
func send(data: PackedByteArray) -> bool:
|
||
|
if _status != _stream.STATUS_CONNECTED:
|
||
|
print("Error: Stream is not currently connected.")
|
||
|
return false
|
||
|
var error: int = _stream.put_data(data)
|
||
|
if error != OK:
|
||
|
print("Error writing to stream: ", error)
|
||
|
return false
|
||
|
|
||
|
return true
|
||
|
|
||
|
func _on_data(data : Array):
|
||
|
var buf = PackedByteArray(data)
|
||
|
var cookie = buf.get_string_from_ascii()
|
||
|
print("Data\t",cookie) # Replace with function body.
|
||
|
self.send(buf)
|
||
|
|
||
|
func _on_connected(s : StreamPeerTCP):
|
||
|
print("Connected to",s.get_connected_host()) # Replace with function body.
|
||
|
|
||
|
func _on_disconnected():
|
||
|
print("Disconnected") # Replace with function body.
|
||
|
|
||
|
func _on_error():
|
||
|
print("Error") # Replace with function body.
|
||
|
|