ServerEvent

This is a library for sending events to the server in synchronous and asynchronous ways optionally waiting for a response.

Communication example

Fires events to the server.

client.lua

-- Gets the server event api.
---@type ServerEventApi
server_event_api = exports.nss_libs:getServerEventApi(GetCurrentResourceName())

Citizen.CreateThread(function()

    local times = 3

    -- Example awaits result and blocks the thread as long as no result response is received.
    -- The server event works like a synchronous function call.
    local data = server_event_api:await("test", times)
    print('Client Result', table.unpack(data))

    -- The callback is executed async on server response.
    -- Example does not await result and does not block the thread. 
    ---@param response_data any|table
    server_event_api:async("test", function(response_data)
        print('Client Result', table.unpack(response_data))
    end, times)

    -- Example fires a global server event and does not wait for a result.
    -- Example does not await result and does not block the thread.
    server_event_api:fire("test", times)

end)

server.lua

Listen events from the client.

"on server ready" example

Executes callback on client side if the server triggers that he is ready.

client.lua

server.lua

You can add arguments to the serverIsReady(true, false, 'whatever') function. The arguments will be passed to the onServerReady callback.

How it works

In client scripts local server_event_api = exports.nss_libs:getServerEventApi(GetCurrentResourceName()) returns a client scoped event api.

That api can be used to fire events to the server. But not to listen to server events (see ClientEvent for that case).

If an event is fired to the server, the server will execute the server side registered listener for that event and return the result. Each fired event has a unique request id. The client will wait for the result with that id and process the result. The server sends the response only to the source client that fired the event.

Last updated

Was this helpful?