2020-09-15 09:30:19 +02:00
|
|
|
extends Node
|
|
|
|
|
|
|
|
signal data_received(string)
|
2021-02-23 13:06:58 +01:00
|
|
|
signal new_connection
|
2020-09-15 09:30:19 +02:00
|
|
|
|
2023-09-06 16:04:23 +02:00
|
|
|
@export var port: int
|
2020-09-15 09:30:19 +02:00
|
|
|
|
2023-09-06 16:04:23 +02:00
|
|
|
var _s = TCPServer.new()
|
2020-09-15 09:30:19 +02:00
|
|
|
var _c
|
|
|
|
var _connected = false
|
|
|
|
|
|
|
|
func _ready():
|
|
|
|
start()
|
|
|
|
|
|
|
|
func start():
|
|
|
|
_s.listen(port)
|
2020-09-24 10:10:14 +02:00
|
|
|
|
2020-09-15 12:36:22 +02:00
|
|
|
func _process(_delta):
|
2020-09-15 09:30:19 +02:00
|
|
|
if _s.is_connection_available():
|
|
|
|
if _connected:
|
2020-09-22 18:53:50 +02:00
|
|
|
_c.disconnect_from_host()
|
2020-09-29 14:53:00 +02:00
|
|
|
helpers.crash("Dropping active connection")
|
2020-09-15 09:30:19 +02:00
|
|
|
_c = _s.take_connection()
|
|
|
|
_connected = true
|
2021-02-23 13:06:58 +01:00
|
|
|
emit_signal("new_connection")
|
2020-09-15 09:30:19 +02:00
|
|
|
print("connected!")
|
|
|
|
|
|
|
|
if _connected:
|
|
|
|
if _c.get_status() != StreamPeerTCP.STATUS_CONNECTED:
|
|
|
|
_connected = false
|
|
|
|
print("disconnected")
|
2021-02-23 13:06:58 +01:00
|
|
|
# var available = _c.get_available_bytes()
|
|
|
|
# while available > 0:
|
|
|
|
# var data = _c.get_utf8_string(available)
|
|
|
|
# emit_signal("data_received", data)
|
|
|
|
# available = _c.get_available_bytes()
|
2020-09-15 09:30:19 +02:00
|
|
|
|
|
|
|
func send(text):
|
|
|
|
if _connected:
|
2020-09-24 10:10:14 +02:00
|
|
|
text += "\n"
|
2021-02-23 13:06:58 +01:00
|
|
|
_c.put_utf8_string(text)
|
|
|
|
var response = _c.get_utf8_string()
|
|
|
|
emit_signal("data_received", response)
|
2020-09-15 09:30:19 +02:00
|
|
|
else:
|
2020-09-29 14:53:00 +02:00
|
|
|
helpers.crash("Trying to send data on closed connection")
|