# ServerManager.gd extends Node var server_path: String = "" var running := false var server_process_id: int = -50 var server_url = "http://localhost:27531" func _ready(): # Get the path to the server directory relative to the project server_path = ProjectSettings.globalize_path("res://Assets/ChessEngines/fairy-chess-server") start_server() get_tree().set_auto_accept_quit(false) func _exit_tree(): stop_server() func _notification(what): if what == NOTIFICATION_WM_CLOSE_REQUEST: stop_server() func start_server() -> bool: if running: return true print("Starting chess server...", server_path) # Make sure we're in the correct directory var http_request = HTTPRequest.new() add_child(http_request) # http_request.connect("request_completed", self._on_init_request_completed) http_request.request_completed.connect(self._on_init_request_completed) http_request.request(server_url + "/health") # var http = HTTPClient.new() # var err = http.connect_to_host("localhost", 27531) # print("is_server_running", err, OK) # if err != OK: # server_process_id = OS.create_process("node", [server_path + "/index.js"]) # if server_process_id <= 0: # printerr("Failed to start server") # return false # if exit_code != 0: # printerr("Failed to start server: ", output) # return false return true func _on_init_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray): print("*****************_on_init_request_completed************") var json = JSON.new() json.parse(body.get_string_from_utf8()) var response = json.get_data() # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org). print(response) if response == null and result != HTTPRequest.RESULT_SUCCESS: print("HTTP Request failed") server_process_id = OS.create_process("node", [server_path + "/index.js"]) if server_process_id <= 0: printerr("Failed to start server") return false running = true print("Chess server started") return running = true if response.status != "ok": print("Server error : ", response_code, json.parse(body.get_string_from_utf8()),) return func stop_server(): if not running: return print("Stopping chess server...") # Send a stop request to the server var headers = ["Content-Type: application/json"] var http = HTTPClient.new() var data = JSON.stringify({"command": "shutdown"}) http.request(HTTPClient.METHOD_POST, "/shutdown", headers, data) running = false print("Chess server stopped") func is_server_running() -> bool: return running