How To Manage Concurrent HTTP Requests in Godot Engine

Photo by Andrew Wulf on Unsplash

How To Manage Concurrent HTTP Requests in Godot Engine

Send many HTTP requests without headache!

ยท

3 min read

Let's learn how to manage concurrent HTTP requests in Godot Engine using a pool of HTTPRequest instances. This approach lets you send multiple requests simultaneously, without thinking the creating HTTP instances or removing them after completed.

Let's See The Code

extends  Node

var instances = {}
var MIN_INSTANCE_COUNT = 4

func _generate_instance_label():
    var chars = 'abcdefghijklmnopqrstuvwxyz'
    var word: String
    var n_char = len(chars)
    for i in range(8):
        word += chars[randi()% n_char]
    return word

func create_instance():
    var instance_label = _generate_instance_label()
    var instance = HTTPRequest.new();
    instances[instance_label]={
        "available": true,
        "instance": instance
    }
    add_child(instance)
    instance.connect("request_completed",Callable(self,"_on_request_completed").bind(instance_label))
    return [instance_label,instance]


func get_instance():
    for instance_label in instances:
        if instances[instance_label]["available"]:
            return [instance_label, instances[instance_label]["instance"]]

    return create_instance()

func get_request(url:String,extra_headers:Array[String]):
    var headers = ["Content-Type: application/json"]
    headers.append_array(extra_headers)
    var instance_obj = get_instance();
    var instance = instance_obj[1]
    instances[instance_obj[0]]["available"] = false
    instance.request(url, headers, HTTPClient.METHOD_GET)
    return instance_obj[0]


func post_request(url:String,data_to_send:Variant,extra_headers:Array[String]):
    var json = JSON.stringify(data_to_send)
    var headers = ["Content-Type: application/json"]
    headers.append_array(extra_headers)
    var instance_obj = get_instance();
    var instance = instance_obj[1]
    instances[instance_obj[0]]["available"] = false
    instance.request(url, headers, HTTPClient.METHOD_POST, json)
    return instance_obj[0]


func _on_request_completed(result, response_code, headers, body,instance_label):    
    if instances.keys().size() > MIN_INSTANCE_COUNT:
        var instance = instances[instance_label]["instance"]
        instances.erase(instance_label)
        remove_child(instance)
    else:
        instances[instance_label]["available"] = true

    print(result, response_code, headers, body,instance_label)

Let's Dive to Code

This GDScript code demonstrates a simple implementation for managing concurrent HTTP requests using Godot Engine's HTTPRequest node. It consists of several functions:

  • _generate_instance_label(): Generates a random label for a new HTTPRequest instance.

  • create_instance(): Creates a new HTTPRequest instance, assigns it a generated label, adds it as a child of the current node, and connects its request_completed signal to the _on_request_completed callback using Callable.bind() to pass the instance label.

  • get_instance(): Retrieves an available HTTPRequest instance from the instances dictionary. If no available instances are found, it calls create_instance() to create a new instance.

  • get_request(url:String,extra_headers:Array[String]): Sends a GET request to the specified URL with optional additional headers. It retrieves an available instance using get_instance(), marks it as unavailable, and sends the GET request using the instance.

  • post_request(url:String,data_to_send:Variant,extra_headers:Array[String]): Sends a POST request to the specified URL with JSON data to be sent in the request body.

  • _on_request_completed(result, response_code, headers, body,instance_label): Callback function called when a request is completed. It prints the result, response code, headers, and body of the response. If the number of instances exceeds MIN_INSTANCE_COUNT, the instance is removed from the pool; otherwise, it is marked as available.

To sum up,

In this tutorial, we explored how to manage concurrent HTTP requests in Godot Engine using a pool of HTTPRequest instances. By utilizing this approach, you can efficiently handle multiple requests simultaneously without having to worry about creating and removing HTTP instances manually. This method streamlines the process of sending and managing HTTP requests without headache. By incorporating this technique into your projects, you can enhance the performance and scalability of your HTTP request handling in Godot Engine.

ย