[SOLVED] What is the best way to share information between client and server? [C# - Lua - JS]

Hi there, I’ve been trying to figure out the best way to exchange information between a client-side and a server-side resource. It often happens (at least in my case) that I need to request a server-side information from the client.
However, I haven’t found an optimal way to do this. The only thing I could think of is triggering a server-side event from the client, and then triggering a client-side event from the server as a response. It would still be much better if there was a more efficient method, but I’m not sure if it’s possible.
Something like this (ideally speaking):

string information = AFunctionThatRetrievesInformationsFromServer(args);

For now I have this:
(I use C# for the examples, but I accept any kind of replies)

ClientMain.cs

TriggerServerEvent("anEvent", somedata);
Eventhandlers["theReply"] += new Action<string>((data) => { Debug.WriteLine(data); })

ServerMain.cs

Eventhandlers["anEvent"] = new Action<Player, string>(AFunction);

...

internal void AFunction([FromSource]Player player, string data)
{
    TriggerClientEvent(player, "theReply", data);
}

Thanks in advance.

You need some kind of callback system to do this. However it is just as you described with triggering server event, then another client event with the data.

ESX and QB come with one already.

I personally built a free one myself to be able to return data inline via exports and with added timeouts (in lua). Feel free to take a look :slight_smile:

1 Like

Actually I’ve just found a native method. They must have been hiding this all the time…

ClientMain.cs

...
TriggerServerEvent("exampleEvent", new Action<object>(arg =>  Debug.WriteLine(arg)));
...

ServerMain.cs

...
EventHandlers["exampleEvent"] += new Action<NetworkCallbackDelegate((networkCB) =>
{
    // the method Invoke makes the callback (the one declared in the client script)
    // been executed client-side.
    networkCB.Invoke("a string that'll be printed out in the client console");
});

You can find more info here.

1 Like