nengi.Channel

A channel allows sending entities and messages to a specific set of clients.

Entities in a channel are seen by all clients in that channel thus bypassing the `client.view`.

Channel API

Updated for v1.9.0

The channel api consists of functions for add/removing entities, clients, and messages.

const channel = instance.createChannel()
// any of the following
channel.addEntity(entity)
channel.removeEntity(entity)
channel.addMessage(message)
channel.subscribe(client)
channel.unsubscribe(client)

// clean up
channel.destroy()

Channel Examples

Room

Some network libraries have a room-like concept where clients and entities join the room and receive data about one another. In nengi this concept is usually the nengi.Instance, but one can also create channels inside of an instance to subdivide things further.

Global State

Want an entity and thus a piece of automatically synchronizing state visible to everyone? Make a channel and add every client to it. Note that the normal limitations of entities still apply - they're just flat objects without arrays or other nested objects inside. If arrays or nested data is needed send messages to the channel.

const globalChannel = instance.createChannel()
globalChannel.addEntity(globalStateEntity)

Then, on connect, for every client:

globalChannel.subscribe(client)

Aso unsubscribe the client from the channel on disconnect to avoid a leak -- this is not done automatically yet.

Team or Party State

Want some state visible to only Red Team? Or Blue Team? Or AdventureParty#62? Create a channel for it, and add just the applicable clients.

Per-Player Private State

Want to have some state that is only ever visible to one client? This can be used to create simple inventory systems, two-entity style client-side prediction, and otherwise network state for just one player.

on connect, for every client:

const channel = instance.createChannel()
channel.subscribe(client)

client.privateChannel = channel
client.myInventory = new Inventory() /* hypothetical */
client.privateChannel.addEntity(client.myInventory)

// later in the game logic...
client.myInventory.coins += 15 /* only this one client will receive this data */

Also remove entities, clients, and the whole channel when the player disconnects. It is worth noting that while the example above shows an inventory system, it isn't much of one. It would only ever consist of flat properties and values, not sophisticated item data. Sophisticated item data would need to be networked via messages instead.