### Server Initialization and Function Definition (Luau) Source: https://github.com/leifstout/networker/blob/main/README.md Demonstrates how to initialize the Networker server instance and define functions accessible by clients. The `init` function sets up the Networker service, and `printTest` is an example of a client-callable function. Ensure Networker is correctly imported and initialized. ```luau local myService = {} function myService:init() -- initialize networker to the service/object self.networker = Networker.server.new("myService", self, { self.printTest, }) end -- client has access to call this because it's included in the client access table function myService:printTest(player: Player) print(`{player.Name} called the print test`) end function myService:addPoints(player: Player, points: number) ... end return myService ``` -------------------------------- ### Synchronize server state using set methods in Luau Source: https://context7.com/leifstout/networker/llms.txt Provides examples for synchronizing data from the server to the client. Includes methods for individual updates, global broadcasts, and recipient-specific state management. ```luau local Networker = require(path.to.Networker) local PlayerDataService = {} function PlayerDataService:init() self.networker = Networker.server.new("PlayerDataService", self, {}) end -- Set a value for a specific player function PlayerDataService:updateCoins(player: Player, coins: number) self.networker:set(player, "coins", coins) end -- Set a value for all players (global game state) function PlayerDataService:updateGamePhase(phase: string) self.networker:setAll("gamePhase", phase) end -- Set for all except specific players function PlayerDataService:updateTeamScore(excludePlayers: {Player}, team: string, score: number) self.networker:setAllExcept(excludePlayers, "teamScores", {[team] = score}) end -- Set for recipients list function PlayerDataService:updateRoomState(state: {[string]: any}) self.networker:setRecipients("roomState", state) end return PlayerDataService ``` -------------------------------- ### Dynamically Add Client Access Methods Source: https://context7.com/leifstout/networker/llms.txt Extends an existing NetworkerServer instance by adding more methods that clients are permitted to call after the initial setup. ```luau local Networker = require(path.to.Networker) local InventoryService = {} function InventoryService:init() self.networker = Networker.server.new("InventoryService", self, { self.getInventory, }) -- Add more client access methods later self.networker:addClientAccess(self, { self.equipItem, self.unequipItem, }) end function InventoryService:getInventory(player: Player) return {"sword", "shield", "potion"} end function InventoryService:equipItem(player: Player, itemName: string) print(`{player.Name} equipped {itemName}`) end function InventoryService:unequipItem(player: Player, itemName: string) print(`{player.Name} unequipped {itemName}`) end return InventoryService ``` -------------------------------- ### Initialize NetworkerClient with Instance-based NetworkTag Source: https://context7.com/leifstout/networker/llms.txt Demonstrates how to initialize a client-side networker using a Roblox Instance as a network tag. The client automatically waits for the server to initialize the tag attribute, facilitating object-oriented network integration. ```luau local Networker = require(path.to.Networker) local VehicleClient = {} VehicleClient.__index = VehicleClient function VehicleClient.new(vehicleModel: Model) local self = setmetatable({ vehicle = vehicleModel, driver = nil, }, VehicleClient) -- Connect using the vehicle instance -- Automatically waits for the server to set up the network tag attribute self.networker = Networker.client.new(vehicleModel, self) return self end -- Called by server when driver changes function VehicleClient:onDriverChanged(driverName: string?) self.driver = driverName if driverName then print(`{driverName} is now driving the vehicle`) else print("Vehicle is now empty") end end -- Request to enter the vehicle function VehicleClient:requestEnter() self.networker:fire("enterVehicle") end -- Request to exit the vehicle function VehicleClient:requestExit() self.networker:fire("exitVehicle") end return VehicleClient ``` -------------------------------- ### Initialize NetworkerServer with Method Whitelisting Source: https://context7.com/leifstout/networker/llms.txt Creates a new NetworkerServer instance to manage server-side networking. It allows developers to define specific methods that are accessible to clients, ensuring secure communication. ```luau local Networker = require(path.to.Networker) -- Define a service with methods local PlayerService = {} function PlayerService:init() -- Create networker with client-accessible methods self.networker = Networker.server.new("PlayerService", self, { self.getPlayerData, self.requestPurchase, }) end -- Client can call this method (whitelisted) function PlayerService:getPlayerData(player: Player) return { coins = 100, level = 5, inventory = {"sword", "shield"} } end -- Client can call this method (whitelisted) function PlayerService:requestPurchase(player: Player, itemId: string) print(`{player.Name} requested to purchase {itemId}`) return true end -- Client CANNOT call this method (not whitelisted) function PlayerService:addCoins(player: Player, amount: number) -- Internal server logic only end return PlayerService ``` -------------------------------- ### Client Networker Initialization and Function Call (Luau) Source: https://github.com/leifstout/networker/blob/main/README.md Shows how to initialize the Networker client instance and fire a server-side function. The `Networker.client.new` function establishes the connection, and `networker:fire("printTest")` invokes the `printTest` function on the server. This requires the server to have exposed the function. ```luau local serviceClient = {} local networker = Networker.client.new("myService", serviceClient) networker:fire("printTest") ``` -------------------------------- ### Create NetworkerClient Instance (Luau) Source: https://context7.com/leifstout/networker/llms.txt Initializes a new NetworkerClient instance to connect to a server-side NetworkerServer. It listens for server events and routes them to the provided module, enabling communication between client and server for game state synchronization. ```luau local Networker = require(path.to.Networker) local GameStateClient = {} -- Properties that will be synced from server via set methods GameStateClient.gamePhase = "waiting" GameStateClient.coins = 0 function GameStateClient:init() -- Connect to the server's GameStateService self.networker = Networker.client.new("GameStateService", self) end -- Called by server via networker:fireAll("onRoundStart", ...) function GameStateClient:onRoundStart(roundNumber: number, duration: number) print(`Round {roundNumber} started! Duration: {duration} seconds`) end -- Called by server via networker:fireAll("onRoundEnd", ...) function GameStateClient:onRoundEnd(winningTeam: string, scores: {[string]: number}) print(`Round ended! Winner: {winningTeam}`) for team, score in scores do print(` {team}: {score}`) end end -- Called by server via networker:fireAll("showAnnouncement", ...) function GameStateClient:showAnnouncement(message: string) -- Display announcement in UI print(`[ANNOUNCEMENT] {message}`) end return GameStateClient ``` -------------------------------- ### Implement instance-based networking in Luau Source: https://context7.com/leifstout/networker/llms.txt Shows how to bind a NetworkerServer to a specific Roblox Instance. This approach automates unique tag generation and ensures cleanup when the instance is destroyed. ```luau local Networker = require(path.to.Networker) local VehicleController = {} VehicleController.__index = VehicleController function VehicleController.new(vehicleModel: Model) local self = setmetatable({ vehicle = vehicleModel, }, VehicleController) -- Use the Instance as the network tag -- Networker automatically generates a unique ID and stores it as an attribute self.networker = Networker.server.new(vehicleModel, self, { self.enterVehicle, self.exitVehicle, }) return self end function VehicleController:enterVehicle(player: Player) print(`{player.Name} entered vehicle`) self.networker:fireAll("onDriverChanged", player.Name) end function VehicleController:exitVehicle(player: Player) print(`{player.Name} exited vehicle`) self.networker:fireAll("onDriverChanged", nil) end -- When vehicleModel:Destroy() is called, the networker automatically cleans up return VehicleController ``` -------------------------------- ### NetworkerServer with Instance-based NetworkTag Source: https://context7.com/leifstout/networker/llms.txt Creates a NetworkerServer tied to a specific Instance, automatically generating a unique tag and cleaning up when the instance is destroyed. ```APIDOC ## NetworkerServer with Instance-based NetworkTag ### Description Creates a NetworkerServer tied to a specific Instance, automatically generating a unique tag and cleaning up when the instance is destroyed. This is useful for managing network state associated with specific game objects like vehicles or interactive elements. ### Initialization `Networker.server.new(instance, self, {callbackMethods})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau local VehicleController = {} VehicleController.__index = VehicleController function VehicleController.new(vehicleModel: Model) local self = setmetatable({ vehicle = vehicleModel }, VehicleController) -- The Instance (vehicleModel) is used as the network tag. -- Networker automatically generates a unique ID and stores it as an attribute. self.networker = Networker.server.new(vehicleModel, self, { self.enterVehicle, self.exitVehicle, }) return self end function VehicleController:enterVehicle(player: Player) print(`{player.Name} entered vehicle`) self.networker:fireAll("onDriverChanged", player.Name) end function VehicleController:exitVehicle(player: Player) print(`{player.Name} exited vehicle`) self.networker:fireAll("onDriverChanged", nil) end -- When vehicleModel:Destroy() is called, the networker automatically cleans up. ``` ### Response #### Success Response (200) Initialization of NetworkerServer with an instance tag. The `Networker.server.new` function returns a Networker instance that can be used to call other network methods. ``` -------------------------------- ### NetworkerClient.new Source: https://context7.com/leifstout/networker/llms.txt Creates a new NetworkerClient instance to connect to a server-side NetworkerServer. It listens for server events and routes them to the provided module. ```APIDOC ## NetworkerClient.new ### Description Creates a new NetworkerClient instance that connects to a server-side NetworkerServer. The client listens for server events and routes them to the provided module. ### Method `Networker.client.new(serviceName: string, eventHandler: object)` ### Endpoint N/A (Client-side initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau local Networker = require(path.to.Networker) local GameStateClient = {} GameStateClient.gamePhase = "waiting" GameStateClient.coins = 0 function GameStateClient:init() self.networker = Networker.client.new("GameStateService", self) end -- ... other methods ... return GameStateClient ``` ### Response #### Success Response (200) N/A (Client-side initialization) #### Response Example N/A ``` -------------------------------- ### NetworkerClient.fetch Source: https://context7.com/leifstout/networker/llms.txt Calls a whitelisted method on the server and yields until the response is received. Use this when you need a return value from the server. ```APIDOC ## NetworkerClient.fetch ### Description Calls a whitelisted method on the server and yields until the response is received. Use this when you need a return value from the server. ### Method `networker:fetch(methodName: string, ...): any` ### Endpoint N/A (Client-to-server communication) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau -- Fetch player data from server (yields) local data = self.networker:fetch("getPlayerData") -- Fetch with arguments local price = self.networker:fetch("getItemPrice", "itemId") ``` ### Response #### Success Response (200) - **data** (any) - The response from the server method. #### Response Example ```json { "coins": 100, "level": 5, "inventory": ["sword", "shield"] } ``` ``` -------------------------------- ### NetworkerServer.set and setAll Source: https://context7.com/leifstout/networker/llms.txt Synchronizes values from server to client. The set methods update a property on the client-side module and trigger change signals. ```APIDOC ## NetworkerServer.set and setAll ### Description Synchronizes values from server to client. The `set` methods update a property on the client-side module and trigger change signals. ### Methods - `set(player, propertyName, value)`: Sets a property for a specific player. - `setAll(propertyName, value)`: Sets a property for all players. - `setAllExcept(excludePlayers, propertyName, value)`: Sets a property for all players except the specified ones. - `setRecipients(propertyName, value)`: Sets a property for all players in the current recipient list. ### Example Usage ```luau -- Set coins for a specific player self.networker:set(player, "coins", coins) -- Set the global game phase for all players self.networker:setAll("gamePhase", phase) -- Update team scores, excluding specific players self.networker:setAllExcept(excludePlayers, "teamScores", {[team] = score}) -- Update the room state for all recipients self.networker:setRecipients("roomState", state) ``` ### Response These methods do not return values directly. They update client-side properties and trigger associated change signals. ``` -------------------------------- ### Fetch Data from Server (Luau) Source: https://context7.com/leifstout/networker/llms.txt Calls a whitelisted method on the server and yields until a response is received, making it ideal for scenarios where a return value is necessary. This method is used to retrieve data like player information, item prices, or leaderboard standings. ```luau local Networker = require(path.to.Networker) local DataClient = {} function DataClient:init() self.networker = Networker.client.new("PlayerService", self) end -- Fetch player data from server (yields) function DataClient:loadPlayerData() local data = self.networker:fetch("getPlayerData") print("Loaded player data:") print(` Coins: {data.coins}`) print(` Level: {data.level}`) print(` Inventory: {table.concat(data.inventory, ", ")}`) return data end -- Fetch with arguments function DataClient:getItemPrice(itemId: string): number local price = self.networker:fetch("getItemPrice", itemId) return price end -- Fetch leaderboard data function DataClient:getLeaderboard(category: string, limit: number) local leaderboard = self.networker:fetch("getLeaderboard", category, limit) for rank, entry in ipairs(leaderboard) do print(`#{rank}: {entry.name} - {entry.score}`) end return leaderboard end return DataClient ``` -------------------------------- ### Broadcast Methods to All Players Source: https://context7.com/leifstout/networker/llms.txt Fires a method call to every connected client simultaneously. This is the standard approach for global events, game state updates, or server-wide announcements. ```luau local Networker = require(path.to.Networker) local GameStateService = {} function GameStateService:init() self.networker = Networker.server.new("GameStateService", self, {}) end function GameStateService:startRound(roundNumber: number) -- Notify all players that the round has started self.networker:fireAll("onRoundStart", roundNumber, 60) -- round number and duration end function GameStateService:endRound(winningTeam: string, scores: {[string]: number}) -- Broadcast round results to everyone self.networker:fireAll("onRoundEnd", winningTeam, scores) end function GameStateService:announceMessage(message: string) self.networker:fireAll("showAnnouncement", message) end -- Usage GameStateService:startRound(1) GameStateService:announceMessage("Welcome to the game!") GameStateService:endRound("Red Team", {["Red Team"] = 150, ["Blue Team"] = 120}) return GameStateService ``` -------------------------------- ### Listen for Server Value Changes (Luau) Source: https://context7.com/leifstout/networker/llms.txt Returns a Signal that fires whenever the server updates a specific value using set methods, facilitating reactive UI updates. This allows clients to subscribe to changes in variables like coins, level, or health and respond accordingly. ```luau local Networker = require(path.to.Networker) local PlayerDataClient = {} -- These values are synced from server PlayerDataClient.coins = 0 PlayerDataClient.level = 1 PlayerDataClient.health = 100 function PlayerDataClient:init() self.networker = Networker.client.new("PlayerDataService", self) -- Listen for coins changes local coinsSignal = self.networker:getServerChangedSignal("coins") coinsSignal:Connect(function(newCoins: number) print(`Coins updated to: {newCoins}`) self:updateCoinsUI(newCoins) end) -- Listen for level changes local levelSignal = self.networker:getServerChangedSignal("level") levelSignal:Connect(function(newLevel: number) print(`Level up! Now level {newLevel}`) self:playLevelUpAnimation() self:updateLevelUI(newLevel) end) -- Listen for health changes self.networker:getServerChangedSignal("health"):Connect(function(newHealth: number) self:updateHealthBar(newHealth) end) end function PlayerDataClient:updateCoinsUI(coins: number) -- Update UI element end function PlayerDataClient:playLevelUpAnimation() -- Play animation end function PlayerDataClient:updateLevelUI(level: number) -- Update UI element end function PlayerDataClient:updateHealthBar(health: number) -- Update health bar UI end return PlayerDataClient ``` -------------------------------- ### Perform Networker Cleanup on Server and Client Source: https://context7.com/leifstout/networker/llms.txt Illustrates the usage of the destroy method to clean up networker instances, which removes remote events and disconnects signals. This ensures memory management and prevents leaks when services or client objects are no longer needed. ```luau -- Server-side cleanup local Networker = require(path.to.Networker) local TemporaryService = {} function TemporaryService:init() self.networker = Networker.server.new("TemporaryService", self, {}) end function TemporaryService:cleanup() -- Destroys remote folder and clears recipients self.networker:destroy() end -- Client-side cleanup local TemporaryClient = {} function TemporaryClient:init() self.networker = Networker.client.new("TemporaryService", self) end function TemporaryClient:cleanup() -- Destroys remotes and disconnects all changed signals self.networker:destroy() end ``` -------------------------------- ### Broadcast messages using fireAllExcept in Luau Source: https://context7.com/leifstout/networker/llms.txt Demonstrates how to send remote events to all connected players while excluding specific individuals or groups. This is essential for preventing redundant notifications to the sender of an action. ```luau local Networker = require(path.to.Networker) local ChatService = {} function ChatService:init() self.networker = Networker.server.new("ChatService", self, { self.sendMessage, }) end function ChatService:sendMessage(player: Player, message: string) -- Broadcast message to everyone except the sender self.networker:fireAllExcept(player, "receiveMessage", player.Name, message) -- Send confirmation to sender self.networker:fire(player, "messageSent", message) end function ChatService:playerAction(player: Player, action: string) -- Notify others that player did something, exclude the player themselves self.networker:fireAllExcept(player, "onPlayerAction", player.Name, action) end -- Exclude multiple players function ChatService:privateTeamMessage(excludePlayers: {Player}, message: string) self.networker:fireAllExcept(excludePlayers, "receiveTeamMessage", message) end return ChatService ``` -------------------------------- ### Fire Methods to Specific Players Source: https://context7.com/leifstout/networker/llms.txt Sends a method call to a specific player or a list of players. This is useful for targeted communication such as private notifications or player-specific updates. ```luau local Networker = require(path.to.Networker) local Players = game:GetService("Players") local NotificationService = {} function NotificationService:init() self.networker = Networker.server.new("NotificationService", self, {}) end -- Fire to a single player function NotificationService:notifyPlayer(player: Player, message: string) self.networker:fire(player, "showNotification", message) end -- Fire to multiple specific players function NotificationService:notifyTeam(players: {Player}, message: string) self.networker:fire(players, "showNotification", message) end -- Usage example local player = Players:FindFirstChild("PlayerName") NotificationService:notifyPlayer(player, "You received a reward!") local teamPlayers = {Players.Player1, Players.Player2} NotificationService:notifyTeam(teamPlayers, "Team objective complete!") return NotificationService ``` -------------------------------- ### Fire Event to Server (Luau) Source: https://context7.com/leifstout/networker/llms.txt Calls a whitelisted method on the server without waiting for a response, functioning as a fire-and-forget operation. This is suitable for actions that do not require immediate feedback from the server, such as sending chat messages or initiating item purchases. ```luau local Networker = require(path.to.Networker) local PlayerServiceClient = {} function PlayerServiceClient:init() self.networker = Networker.client.new("PlayerService", self) end -- Fire a request to the server (no return value) function PlayerServiceClient:requestPurchase(itemId: string) self.networker:fire("requestPurchase", itemId) end -- Fire with multiple arguments function PlayerServiceClient:sendChatMessage(channel: string, message: string) self.networker:fire("sendMessage", channel, message) end -- Fire action events function PlayerServiceClient:equipItem(itemName: string) self.networker:fire("equipItem", itemName) end -- Usage in UI button handler local function onPurchaseButtonClicked() PlayerServiceClient:requestPurchase("golden_sword") end return PlayerServiceClient ``` -------------------------------- ### NetworkerClient.fire Source: https://context7.com/leifstout/networker/llms.txt Calls a whitelisted method on the server without waiting for a response. This is a fire-and-forget operation. ```APIDOC ## NetworkerClient.fire ### Description Calls a whitelisted method on the server without waiting for a response. This is a fire-and-forget operation. ### Method `networker:fire(methodName: string, ...)` ### Endpoint N/A (Client-to-server communication) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau -- Fire a request to the server (no return value) self.networker:fire("requestPurchase", "itemId") -- Fire with multiple arguments self.networker:fire("sendMessage", "channel", "message") ``` ### Response #### Success Response (200) N/A (Fire-and-forget) #### Response Example N/A ``` -------------------------------- ### NetworkerServer.fireAllExcept Source: https://context7.com/leifstout/networker/llms.txt Fires a method to all players except the specified player(s). This is useful for events where the triggering player should not receive the notification. ```APIDOC ## NetworkerServer.fireAllExcept ### Description Fires a method to all players except the specified player(s). Useful for events where the triggering player shouldn't receive the notification. ### Method `fireAllExcept(excludePlayers, methodName, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau -- Example usage within a service: self.networker:fireAllExcept(player, "receiveMessage", player.Name, message) self.networker:fireAllExcept(excludePlayers, "receiveTeamMessage", message) ``` ### Response #### Success Response (200) This method does not return a value directly. It triggers a remote event on the client(s). ``` -------------------------------- ### NetworkerClient.getServerChangedSignal Source: https://context7.com/leifstout/networker/llms.txt Returns a Signal that fires whenever the server updates a specific value using the set methods. Useful for reactive UI updates. ```APIDOC ## NetworkerClient.getServerChangedSignal ### Description Returns a Signal that fires whenever the server updates a specific value using the set methods. Useful for reactive UI updates. ### Method `networker:getServerChangedSignal(propertyName: string): Signal` ### Endpoint N/A (Client-side event listening) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```luau -- Listen for coins changes local coinsSignal = self.networker:getServerChangedSignal("coins") coinsSignal:Connect(function(newCoins: number) print(`Coins updated to: {newCoins}`) end) -- Listen for level changes self.networker:getServerChangedSignal("level"):Connect(function(newLevel: number) print(`Level up! Now level {newLevel}`) end) ``` ### Response #### Success Response (200) - **Signal** (Signal) - A Roblox Signal object that fires with the new value when the specified property changes on the server. #### Response Example N/A (Returns a Signal object) ``` -------------------------------- ### NetworkerServer Recipients System Source: https://context7.com/leifstout/networker/llms.txt Manages a persistent list of recipient players for targeted broadcasts. Useful for room-based or team-based messaging without repeatedly specifying players. ```APIDOC ## NetworkerServer Recipients System ### Description Manages a persistent list of recipient players for targeted broadcasts. Useful for room-based or team-based messaging without repeatedly specifying players. ### Methods - `addRecipient(player)`: Adds a player to the persistent recipient list. - `removeRecipient(player)`: Removes a player from the persistent recipient list. - `clearRecipients()`: Clears all players from the persistent recipient list. - `fireRecipients(methodName, ...)`: Fires a method to all players currently in the recipient list. ### Example Usage ```luau -- Add a player to the room self.networker:addRecipient(player) -- Notify all room members about the new player self.networker:fireRecipients("onPlayerJoined", player.Name) -- Remove a player from the room self.networker:removeRecipient(player) self.networker:fireRecipients("onPlayerLeft", player.Name) -- Broadcast a message to the room self.networker:fireRecipients("roomMessage", message) -- Clear the room self.networker:clearRecipients() ``` ### Response These methods do not return values directly. They manage the recipient list and trigger remote events on the clients in the list. ``` -------------------------------- ### Manage persistent recipient lists in Luau Source: https://context7.com/leifstout/networker/llms.txt Utilizes the recipient system to maintain a dynamic list of players for targeted broadcasts. This pattern is ideal for room-based or team-specific messaging systems. ```luau local Networker = require(path.to.Networker) local RoomService = {} function RoomService:init() self.networker = Networker.server.new("RoomService", self, {}) end function RoomService:playerJoinRoom(player: Player) self.networker:addRecipient(player) -- Notify all room members about the new player self.networker:fireRecipients("onPlayerJoined", player.Name) end function RoomService:playerLeaveRoom(player: Player) self.networker:removeRecipient(player) self.networker:fireRecipients("onPlayerLeft", player.Name) end function RoomService:broadcastToRoom(message: string) self.networker:fireRecipients("roomMessage", message) end function RoomService:resetRoom() -- Clear all recipients when room resets self.networker:clearRecipients() end return RoomService ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.