Receiving Network Messages
cLib.Net.Receive
Register a handler for incoming messages.
cLib.Net.Receive(name, callback)Callback Parameters:
| Realm | Parameter 1 | Parameter 2 |
|---|---|---|
| Client | data (table) | - |
| Server | data (table) | ply (Player) |
Client Examples
cLib.Net.SetPrefix("MyAddon.")
-- Simple receive
cLib.Net.Receive("Notification", function(data)
notification.AddLegacy(data.message, NOTIFY_GENERIC, 3)
end)
-- Update local data
cLib.Net.Receive("SyncInventory", function(data)
LocalPlayer().inventory = data.items
LocalPlayer().money = data.money
-- Update UI if open
if IsValid(MyAddon.InventoryPanel) then
MyAddon.InventoryPanel:Refresh()
end
end)
-- Handle results
cLib.Net.Receive("PurchaseResult", function(data)
if data.success then
surface.PlaySound("buttons/button15.wav")
cLib.Alert("Success", "Item purchased!", "OK")
else
surface.PlaySound("buttons/button10.wav")
cLib.Alert("Error", data.error or "Purchase failed", "OK")
end
end)Server Examples
cLib.Net.SetPrefix("MyAddon.")
-- Validate incoming data
cLib.Net.Receive("UpdateSettings", function(data, ply)
-- Always validate!
if not IsValid(ply) then return end
if not ply:IsAdmin() then return end
if type(data.setting) ~= "string" then return end
if type(data.value) == nil then return end
-- Process valid data
SaveSetting(ply, data.setting, data.value)
end)
-- Rate-limited action
local lastRequest = {}
cLib.Net.Receive("RequestData", function(data, ply)
local steamid = ply:SteamID64()
local now = CurTime()
-- Rate limit: 1 request per second
if lastRequest[steamid] and now - lastRequest[steamid] < 1 then
return
end
lastRequest[steamid] = now
-- Process request
local result = GetDataForPlayer(ply, data.type)
cLib.Net.Send("DataResponse", result, ply)
end)Error Handling
cLib.Net.Receive("ImportantData", function(data)
-- Check data exists
if not data then
cLib.Debug.Error("Received nil data")
return
end
-- Check required fields
if not data.id or not data.value then
cLib.Debug.Warn("Missing required fields in data")
return
end
-- Safe to process
ProcessData(data)
end)