Start typing to search packages!
switch
By @yakoplayz
Roblox
Mirrored from WallySwitch
Compact, zero-dependency, frame-batched fire/invoke networking for Roblox over two shared remotes (RemoteEvent and UnreliableRemoteEvent).
Designed for high-throughput multiplayer games, Switch routes all client-server traffic across 256 numeric channels (0–255), automatically batches packets per Heartbeat, chunks unreliable payloads under Roblox's 900-byte MTU, inlines buffer payloads directly into binary streams, and provides non-blocking, timeout-safe RPCs (InvokeServer / InvokeClient).
Features
- Zero Dependencies: Self-contained single-file module with full
--!strictLuau types. - Automatic Frame Batching: Queues outgoing calls and flushes them in a single remote invocation per
Heartbeat. - Inline Binary Buffers: Any
bufferpayload (such as serializedSerapackets) is packed directly into the binary header stream with zero table wrapper overhead. - Unreliable MTU Protection: Automatically splits
Switch.Unreliablebatches into<= 850-byte chunks so multi-packet frames never exceed Roblox's~900-byte unreliable limit. - Safe RPCs (
InvokeServer/InvokeClient): Event-backed request/response calls with configurable timeouts,xpcalltracebacks, automaticPlayerDisconnectedcancellation, and explicit error codes ("Timeout","HandlerError","UnhandledChannel","PlayerDisconnected"). - Pre-Boot Packet Queuing: Buffers up to
64early reliable packets per channel on the client until the first listener binds, without replaying stale packets after a disconnect. - Built-In Flood Protection: Drops incoming client packets exceeding
120packets/sec per player.
Installation
Add Switch to your wally.toml:
[dependencies]
Switch = "yakoplayz/switch@0.1.0"
Then run wally install.
Setup & Initialization
- Server (
Server/init.server.luau): RequireSwitchon boot so_SwitchReliableand_SwitchUnreliableare created before any client joins. - Client (
Client.client.luau): CallSwitch.Connect()once on startup before binding listeners or booting services. (Note:Switch.Connect()yields until remotes replicate—do not call it inside a non-yielding loader phase).
-- Server
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Switch = require(ReplicatedStorage.Packages.Switch)
-- Client
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Switch = require(ReplicatedStorage.Packages.Switch)
Switch.Connect()
Quick Start
1. Define Shared Channels (Channels.luau)
Keep channel IDs (0–255) in a shared ModuleScript so server and client never collide or hardcode raw numbers:
--!strict
return table.freeze({
Chat = 1,
Position = 2,
GetProfile = 3,
})
2. One-Way Events (Fire & OnFire)
-- Server
Switch.OnServerFire(Channels.Chat, function(player: Player, message: unknown)
if typeof(message) ~= "string" or #message > 200 then
return
end
Switch.FireClient(Channels.Chat, "All", `{player.Name}: {message}`)
end)
-- High-frequency unreliable broadcast
Switch.FireClient(Channels.Position, "All", positionBuffer, Switch.Unreliable)
-- Client
local disconnect = Switch.OnClientFire(Channels.Chat, function(formattedMessage: string)
print(formattedMessage)
end)
Switch.FireServer(Channels.Chat, "Hello world!")
-- Call disconnect() (or pass to Janitor:Add) when cleaning up
3. Request / Response RPCs (Invoke & OnInvoke)
-- Server
Switch.OnServerInvoke(Channels.GetProfile, function(player: Player, _payload: unknown)
return { coins = 250, level = 5 }
end)
-- Client (must run in a thread that is allowed to yield)
local ok, result = Switch.InvokeServer(Channels.GetProfile, nil, 5)
if ok then
print("Coins:", result.coins)
else
warn("Invoke failed:", result) -- "Timeout" | "HandlerError" | "UnhandledChannel"
end
API Reference
Constants
| Property | Value | Description |
|---|---|---|
Switch.Reliable | 0 | Sends packets over the reliable RemoteEvent (default). |
Switch.Unreliable | 1 | Sends packets over the UnreliableRemoteEvent (faster, no head-of-line blocking, may drop). |
Lifecycle
Switch.Connect()
Binds the client to Switch's remotes and starts per-frame Heartbeat flushing. Yields up to 15 seconds if remotes have not replicated yet. No-op on the server.
Firing Packets
Switch.FireClient(channelId: number, target: Player | "All" | { Player }, payload: any, reliability: number?)
(Server-only) Queues a one-way packet to a single Player, an array of Players, or "All". Defaults to Switch.Reliable.
Switch.FireServer(channelId: number, payload: any, reliability: number?)
(Client-only) Queues a one-way packet to the server. Defaults to Switch.Reliable.
Switch.OnClientFire(channelId: number, callback: (payload: any) -> ()): () -> ()
(Client-only) Registers a listener for both reliable and unreliable packets on channelId. Flushes any buffered pre-boot reliable packets on first bind. Returns a disconnect function.
Switch.OnServerFire(channelId: number, callback: (player: Player, payload: any) -> ()): () -> ()
(Server-only) Registers a listener for both reliable and unreliable packets on channelId. Returns a disconnect function.
Invoking (RPCs)
Switch.InvokeServer(channelId: number, payload: any, timeoutSeconds: number?, reliability: number?): (boolean, any)
(Client-only, yields) Invokes the server and returns (true, result) or (false, errorReason). Default timeout is 10 seconds.
Switch.InvokeClient(channelId: number, targetPlayer: Player, payload: any, timeoutSeconds: number?, reliability: number?): (boolean, any)
(Server-only, yields) Invokes a specific client and returns (true, result) or (false, errorReason). Automatically resolves with (false, "PlayerDisconnected") if the player leaves mid-request.
Switch.OnServerInvoke(channelId: number, callback: (player: Player, payload: any) -> any): () -> ()
(Server-only) Binds the single RPC handler for channelId (warns if overwriting an existing handler). Returns a disconnect function.
Switch.OnClientInvoke(channelId: number, callback: (payload: any) -> any): () -> ()
(Client-only) Binds the single RPC handler for channelId (warns if overwriting an existing handler). Returns a disconnect function.
Recommendations & Best Practices
- Pair with
Serafor High-Frequency Data: Switch is serialization-agnostic. For 30–60 Hz movement, physics, or combat replication, pack your data into abufferusingSerabefore callingFireClient/FireServer—Switch will inline thebufferdirectly into its binary stream with zero table overhead. - Validate Every Client Payload: Switch validates packet headers and rate limits incoming packets, but never trusts payload contents. Always validate types, buffer lengths,
NaNvalues (x ~= x), and ranges insideOnServerFireandOnServerInvoke. - Keep Unreliable Payloads Small: Multi-packet batches on
Switch.Unreliableare automatically split under850bytes, but an individual payload larger than~850bytes will be dropped by Roblox'sUnreliableRemoteEvent. UseSwitch.Reliablefor large or critical payloads. - Use Reliable Invokes by Default: Leave the
reliabilityargument omitted (Switch.Reliable) onInvokeServer/InvokeClientunless you specifically want dropped requests/replies to fail with"Timeout".
License
MIT
Package Details
Install command (Click to copy)
Version
0.1.1
License
MIT
Safe for commercial use
The package archive does not include its license text; the license is declared in its manifest metadata.
Automated license review — not legal advice.
