Forest Logo
search
package_2

switch

By @yakoplayz

Roblox

Mirrored from Wally

Switch

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 --!strict Luau types.
  • Automatic Frame Batching: Queues outgoing calls and flushes them in a single remote invocation per Heartbeat.
  • Inline Binary Buffers: Any buffer payload (such as serialized Sera packets) is packed directly into the binary header stream with zero table wrapper overhead.
  • Unreliable MTU Protection: Automatically splits Switch.Unreliable batches 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, xpcall tracebacks, automatic PlayerDisconnected cancellation, and explicit error codes ("Timeout", "HandlerError", "UnhandledChannel", "PlayerDisconnected").
  • Pre-Boot Packet Queuing: Buffers up to 64 early 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 120 packets/sec per player.

Installation

Add Switch to your wally.toml:

[dependencies]
Switch = "yakoplayz/switch@0.1.0"

Then run wally install.


Setup & Initialization

  1. Server (Server/init.server.luau): Require Switch on boot so _SwitchReliable and _SwitchUnreliable are created before any client joins.
  2. Client (Client.client.luau): Call Switch.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

PropertyValueDescription
Switch.Reliable0Sends packets over the reliable RemoteEvent (default).
Switch.Unreliable1Sends 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

  1. Pair with Sera for High-Frequency Data: Switch is serialization-agnostic. For 30–60 Hz movement, physics, or combat replication, pack your data into a buffer using Sera before calling FireClient / FireServer—Switch will inline the buffer directly into its binary stream with zero table overhead.
  2. Validate Every Client Payload: Switch validates packet headers and rate limits incoming packets, but never trusts payload contents. Always validate types, buffer lengths, NaN values (x ~= x), and ranges inside OnServerFire and OnServerInvoke.
  3. Keep Unreliable Payloads Small: Multi-packet batches on Switch.Unreliable are automatically split under 850 bytes, but an individual payload larger than ~850 bytes will be dropped by Roblox's UnreliableRemoteEvent. Use Switch.Reliable for large or critical payloads.
  4. Use Reliable Invokes by Default: Leave the reliability argument omitted (Switch.Reliable) on InvokeServer / InvokeClient unless 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

check_circle

Safe for commercial use

infoThe package archive does not include its license text; the license is declared in its manifest metadata.

Automated license review — not legal advice.