Network¶
Plugins on the server and on its players can exchange messages over named channels. A server plugin and a client plugin only need to agree on the channel name.
Messages go from a client to the server, or from the server to one or all clients. Clients cannot send messages to each other directly; the server has to relay them.
- A payload is a string of up to 476 bytes. It may hold binary data. Longer payloads are not sent, so larger data must be split by the sender.
- Payloads from clients are not trusted; validate them on the server.
Functions¶
Balltze.network.subscribe¶
Balltze.network.subscribe(channel, listener)
Calls listener(payload, senderPlayerIndex) for every message received on channel. On the
server, senderPlayerIndex is the index of the player that sent it. On a client it is nil,
since only the server sends messages to clients. Several plugins can listen to the same channel.
Listeners are removed when the plugin unloads. There is no function to remove one before that.
Balltze.network.send¶
local sent = Balltze.network.send(channel, payload)
Client only. Sends a payload to the server. Returns false when there is no connection to a
server or the payload is too long.
Balltze.network.sendToPlayer¶
local sent = Balltze.network.sendToPlayer(playerIndex, channel, payload)
Server only. Sends a payload to one player. Returns false when not running as the server or
the payload is too long.
Balltze.network.broadcast¶
local sent = Balltze.network.broadcast(channel, payload)
Server only. Sends a payload to every player. Returns false when not running as the server or
the payload is too long.
Example¶
Tip
Channels are identified by a hash of their name, so prefix them with your plugin name to avoid clashing with other plugins.
-- On the server: answer every ping with a pong.
Balltze.network.subscribe("my-plugin:ping", function(payload, senderPlayerIndex)
Balltze.network.sendToPlayer(senderPlayerIndex, "my-plugin:pong", payload)
end)
-- On the client: print the answer.
Balltze.network.subscribe("my-plugin:pong", function(payload)
Engine.terminal.print("pong: {}", payload)
end)
Balltze.network.send("my-plugin:ping", "hello")