nengi.Client

Updated for v1.0.0

A nengi.Client can connect to an instance, from which it can receive game data, and to which it can send commands.

Client API at a glance

// construct the client
const client = new nengi.Client(nengiConfig, interpDelay)

// connection callback
client.onConnect(res => {
    console.log('onConnect response:', res)
})

// connection closed callback
client.onClose(() => {
    console.log('connection closed')
})

// connect to a server
client.connect(serverAddress, optionalData)

// send commands to the server
client.addCommand(command)
client.update() // flushes commands, sending them to the server

// read data from the server
let network = client.readNetwork()

client.connect(serverAddress, optionalData)

The serverAddress is a websocket address, e.g. 'ws://127.0.0.1:8080'. The optionalData is an object that can be passed to the server along with our connection (JSON). This can be used to authenticate our user (via a token) or simply tell the server some little piece of information such as our username. This data cannot truly be trusted however, as it orignates from the client and thus can be tampered with. See the instance.onConnect api for the recipient of this data.

Commands

See the manual page for Command for more information.

client.readNetwork()

Data coming from the server contains entities and messages.

The following manual pages show the data that can come through in each section: Entity, Message, and LocalMessage.

let network = this.client.readNetwork()

network.entities.forEach(snapshot => {
    snapshot.createEntities.forEach(entity => {
        console.log('create a new entity', entity)
    })

    snapshot.updateEntities.forEach(update => {
        console.log('update something about an existing entity', update)
    })

    snapshot.deleteEntities.forEach(id => {
        console.log('delete an entity', id)
    })
})

network.messages.forEach(message => {
    console.log('message', message)
})

network.localMessages.forEach(localMessage => {
    console.log('localMessage', localMessage)
})

client.readNetwork() should be called every frame, and the create, update, delete, message, and localMessage data should be used to render the state of the game.

A future version of nengi may do away with the distinction between messages and localMessages, thus reducing the api to just entities and messages.