nengi.Client

Updated for v0.3.3

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
let 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 connection callback will fire (async) returning the server's response. The optionalData is an object that can be passed to the server along with our connection. 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.

Commands are the messages that are sent from game clients to the game server. Commands are bundled together per frame. Invoking addCommand(someCommand) merely adds it to a queue, and then client.update() does the actual sending of the commands that have been queued up.

client.readNetwork()

Data from the server comes in 2 flavors: entity snapshots, and messages. Entity update data has gone through an interpolator, and is therefore smooth.

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', entity)
    })

    snapshot.updateEntities.forEach(update => {
        console.log('update', update)
    })

    snapshot.deleteEntities.forEach(id => {
        console.log('delete', 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.