diff options
Diffstat (limited to 'client/server.gd')
-rw-r--r-- | client/server.gd | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/client/server.gd b/client/server.gd new file mode 100644 index 00000000..c935b645 --- /dev/null +++ b/client/server.gd @@ -0,0 +1,84 @@ +class_name GameServer +extends Node + +var thread = null +var pid = null + +var state = State.TESTING +enum State { + TESTING, + UNAVAILABLE, + STOPPED, + STARTING, + RUNNING, +} + +var sem = Semaphore.new() +var thread_result = null; + +func _ready(): + state = State.TESTING + thread = Thread.new() + thread.start(_test_server) + + +func start(): + if state != State.STOPPED: + push_error("server cant be started") + return + state = State.STARTING + thread = Thread.new() + thread.start(_server_exec) + +func stop(): + if state != State.RUNNING: + push_error("server cant be stopped") + return + OS.kill(pid) + +func _test_server(): + var output = [] + thread_result = OS.execute("undercooked-server", ["version"], output, true, false) + sem.post() + +func _server_exec(): + thread_result = OS.create_process("undercooked-server", [], false) + if thread_result >= 0: + var ok = false + while not ok: + var conn = StreamPeerTCP.new() + if conn.connect_to_host("127.0.0.1", 27032) == OK: + while conn.poll() == OK: + if conn.get_status() == StreamPeerTCP.STATUS_ERROR: break + elif conn.get_status() == StreamPeerTCP.STATUS_CONNECTED: ok = true; break + OS.delay_msec(10) + OS.delay_msec(500 if not ok else 50) + sem.post() + +func _process(_delta): + match state: + State.TESTING: + if sem.try_wait(): + print("Server: Test result=", thread_result) + if thread_result == 0: state = State.STOPPED + else: state = State.UNAVAILABLE + thread.wait_to_finish() + thread = null + State.STARTING: + if sem.try_wait(): + if thread_result >= 0: + state = State.RUNNING + pid = thread_result + print("Server: Started pid=", thread_result) + else: state = State.STOPPED + thread.wait_to_finish() + thread = null + State.RUNNING: + if not OS.is_process_running(pid): + print("Server: Stopped") + state = State.STOPPED + pid = null + +func _exit_tree(): + if thread != null: thread.wait_to_finish() + if pid != null: OS.kill(pid) |