Events between client and server
How to register custom events with addEvent and send them between client and server using triggerServerEvent, triggerClientEvent and latent events in MY Multiplayer (MYMP).
In MY Multiplayer (MYMP), client and server scripts communicate across the network by registering custom events and triggering them on the opposite side.
Creating and listening for an event
addEvent(name, remote)registers an event name. Only an event created withremoteset totruecan arrive over the network from the other side; any other incoming remote event is dropped and logged.addEventHandler(name, element, callback)attaches a Lua handler function to the event on the element tree.
From the client to the server
triggerServerEvent(name, source, ...) sends an event from the client to the server.
- Server-known elements only:
sourceand any elements passed as arguments must exist on the server. Passing a client-only element raises an error. - Sender verification: on the server, the global variable
clientholds the player whose connection sent the packet. Always rely onclient— neversourceor a handler argument — to identify who sent the event, because the client chooses bothsourceand the arguments.
From the server to the client
triggerClientEvent([to,] name, source, ...) sends an event from the server to one or more clients:
to: a singleplayer, a table of players or any element in the tree (sending to every player below it). When omitted, the event goes to every connected player.- For large payloads,
triggerLatentServerEventandtriggerLatentClientEventtransfer data gradually within a bandwidth limit.
Complete example
Server:
addEvent("onShopBuy", true)
addEventHandler("onShopBuy", resourceRoot, function(itemId)
if type(itemId) ~= "string" then return end
triggerClientEvent(client, "onShopBought", resourceRoot, itemId)
end)Client:
addEvent("onShopBought", true)
addEventHandler("onShopBought", resourceRoot, function(itemId)
outputDebugString("You bought " .. itemId)
end)
triggerServerEvent("onShopBuy", resourceRoot, "burger")Per-player rate limit
A player who triggers more than max_player_triggered_events_per_interval events (default: 100) within player_triggered_event_interval ms (default: 1000, both configured in server.cfg) causes the server to fire onPlayerTriggerEventThreshold. What happens next is up to the script — for example disconnecting the player with kickPlayer.