Skip to content

heroiclabs/nakama-defold

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nakama Defold/Lua client

Lua client for Nakama server written in Lua 5.1.

Nakama is an open-source server designed to power modern games and apps. Features include user accounts, chat, social, matchmaker, realtime multiplayer, and much more.

This client implements the full API and socket options with the server. It's written in Lua 5.1 to be compatible with Lua based game engines.

Full documentation is available here.

Getting Started

You'll need to setup the server and database before you can connect with the client. The simplest way is to use Docker but have a look at the server documentation for other options.

  1. Install and run the servers. Follow these instructions.

  2. Add the client to your project.

  • In Defold projects you need to add the URL of a stable release or the latest development version as a library dependency to game.project. The client will now show up in nakama folder in your project.
  1. Add dependencies to your project. In Defold projects you need to add one of the following dependencies to game.project:

  2. Use the connection credentials to initialise the nakama client.

    local defold = require "nakama.engine.defold"
    local nakama = require "nakama.nakama"
    local config = {
        host = "127.0.0.1",
        port = 7350,
        use_ssl = false,
        username = "defaultkey",
        password = "",
        engine = defold,
        timeout = 10, -- connection timeout in seconds
    }
    local client = nakama.create_client(config)
  3. (Optional) Nakama uses base64 decoding for session the session tokens and both base64 encoding and decoding of match data. The default base64 encoder and decoder is written in Lua. To increase performance of the base64 encode and decode steps it is possible to use a base64 encoder written in C. In Defold projects you need to add the following dependency to game.project:

Usage

The client has many methods to execute various features in the server or open realtime socket connections with the server.

Authenticate

There's a variety of ways to authenticate with the server. Authentication can create a user if they don't already exist with those credentials. It's also easy to authenticate with a social profile from Google Play Games, Facebook, Game Center, etc.

local client = nakama.create_client(config)

local email = "super@heroes.com"
local password = "batsignal"
local session = client.authenticate_email(email, password)
pprint(session)

Note: see Requests section below for running this snippet (a)synchronously.

Sessions

When authenticated the server responds with an auth token (JWT) which can be used to authenticate API requests. The token contains useful properties and gets deserialized into a session table.

local client = nakama.create_client(config)

local session = client.authenticate_email(email, password)

print(session.created)
print(session.token) -- raw JWT token
print(session.expires)
print(session.user_id)
print(session.username)
print(session.refresh_token) -- raw JWT token for use when refreshing the session
print(session.refresh_token_expires)
print(session.refresh_token_user_id)
print(session.refresh_token_username)

-- Use the token to authenticate future API requests
nakama.set_bearer_token(client, session.token)

-- Use the refresh token to refresh the authentication token
nakama.session_refresh(client, session.refresh_token)

It is recommended to store the auth token from the session and check at startup if it has expired. If the token has expired you must reauthenticate. If the token is about to expire it has to be refreshed. The expiry time of the token can be changed as a setting in the server. You can store the session using session.store(session) and later restored it using session.restore():

local nakama_session = require "nakama.session"

local client = nakama.create_client(config)

-- restore a session
local session = nakama_session.restore()

if session and nakama_session.is_token_expired_soon(session) and not nakama.is_refresh_token_expired(session) then
    print("Session has expired or is about to expire. Refreshing.")
    session = nakama.session_refresh(client, session.refresh_token)
    nakama_session.store(session)
elseif not session or nakama_session.is_refresh_token_expired(session) then
    print("Session does not exist or it has expired. Must reauthenticate.")
    session = client.authenticate_email("bjorn@defold.se", "foobar123", nil, true, "britzl")
    nakama_session.store(session)
end
client.set_bearer_token(session.token)

Requests

The client includes lots of built-in APIs for various features of the game server. These can be accessed with the methods which either use a callback function to return a result (ie. asynchronous) or yield until a result is received (ie. synchronous and must be run within a Lua coroutine).

local client = nakama.create_client(config)

-- using a callback
client.get_account(function(account)
    print(account.user.id);
    print(account.user.username);
    print(account.wallet);
end)

-- if run from within a coroutine
local account = client.get_account()
print(account.user.id);
print(account.user.username);
print(account.wallet);

The Nakama client provides a convenience function for creating and starting a coroutine to run multiple requests synchronously one after the other:

nakama.sync(function()
    local account = client.get_account()
    local result = client.update_account(request)
end)

Retries

Nakama has a global and per-request retry configuration to control how failed API calls are retried.

    local retries = require "nakama.util.retries"

    -- use a global retry policy with 5 attempts with 1 second intervals
    local config = {
        host = "127.0.0.1",
        port = 7350,
        username = "defaultkey",
        password = "",
        retry_policy = retries.fixed(5, 1),
        engine = defold,
    }
    local client = nakama.create_client(config)

    -- use a retry policy specifically for this request
    -- 5 retries at intervals increasing by 1 second between attempts (eg 1s, 2s, 3s, 4s, 5s)
    nakama.list_friends(client, 10, 0, "", retries.incremental(5, 1))

Cancelling requests

Create a cancellation token and pass that with a request to cancel the request before it has completed.

    -- use a global retry policy with 5 attempts with 1 second intervals
    local config = {
        host = "127.0.0.1",
        port = 7350,
        username = "defaultkey",
        password = "",
        retry_policy = retries.fixed(5, 1),
        engine = defold,
    }
    local client = nakama.create_client(config)

    -- create a cancellation token
    local token = nakama.cancellation_token()

    -- start a request and proivide the cancellation token
    nakama.list_friends(client, 10, 0, "", nil, callback, token)

    -- immediately cancel the request without waiting for the request callback to be invoked
    nakama.cancel(token)

Socket

You can connect to the server over a realtime WebSocket connection to send and receive chat messages, get notifications, and matchmake into a multiplayer match.

You first need to create a realtime socket to the server:

local client = nakama.create_client(config)

-- create socket
local socket = client.create_socket()

nakama.sync(function()
    -- connect
    local ok, err = socket.connect()
end)

Then proceed to join a chat channel and send a message:

-- send channel join message
local channel_id = "pineapple-pizza-lovers-room"
local result = socket.channel_join(socket, 1, channel_id, false, false)

-- send channel messages
local result = socket.channel_message_send(channel_id, "Pineapple doesn't belong on a pizza!")

Handle events

A client socket has event listeners which are called on various events received from the server. Example:

socket.on_disconnect(function(message)
    print("Disconnected!")
end)

Available listeners:

  • on_disconnect - Handles an event for when the client is disconnected from the server.
  • on_channel_presence_event
  • on_match_presence_event
  • on_match_data
  • on_match
  • on_matchmaker_matched
  • on_notifications
  • on_party_presence_event
  • on_party
  • on_party_data
  • on_party_join_request
  • on_status_presence_event
  • on_status
  • on_stream_data
  • on_error
  • on_channel_message
  • on_channel_message

Match data

Nakama supports any binary content in data attribute of a match message. Regardless of your data type, the server only accepts base64-encoded data, so make sure you don't post plain-text data or even JSON, or Nakama server will claim the data malformed and disconnect your client (set server logging to debug to detect these events).

Nakama will automatically base64 encode your match data if the message was created using nakama.create_match_data_message(). Nakama will also automatically base64 decode any received match data before calling the on_matchdata listener.

local json = require "nakama.util.json"

local match_id = "..."
local op_code = 1
local data = json.encode({
    dest_x = 1.0,
    dest_y = 0.1,
})

-- send a match data message. The data will be automatically base64 encoded.
socket.match_data(match_id, op_code, data)

In a relayed multiplayer, you'll be receiving other clients' messages. The client has already base64 decoded the message data before sending it to the on_matchdata listener. If the data was JSON encoded, like in the example above, you need to decode it yourself:

socket.on_matchdata(function(message)
    local match_data = message.match_data
    local data = json.decode(match_data.data)
    pprint(data)                            -- gameplay coordinates from the example above
end)

Messages initiated by the server in an authoritative match will come as valid JSON by default.

Adapting to other engines

Adapting the Nakama Defold client to another Lua based engine should be as easy as providing another engine module when configuring the Nakama client:

local myengine = require "nakama.engine.myengine"
local nakama = require "nakama.nakama"
local config = {
    engine = myengine,
}
local client = nakama.create_client(config)

The engine module must provide the following functions:

  • http(config, url_path, query_params, method, post_data, cancellation_token, callback) - Make HTTP request.

    • config - Config table passed to nakama.create()
    • url_path - Path to append to the base uri
    • query_params - Key-value pairs to use as URL query parameters
    • method - "GET", "POST"
    • post_data - Data to post
    • cancellation_token - Check if cancellation_token.cancelled is true
    • callback - Function to call with result (response)
  • socket_create(config, on_message) - Create socket. Must return socket instance (table with engine specific socket state).

    • config - Config table passed to nakama.create()
    • on_message - Function to call when a message is sent from the server
  • socket_connect(socket, callback) - Connect socket.

    • socket - Socket instance returned from socket_create()
    • callback - Function to call with result (ok, err)
  • socket_send(socket, message, callback) - Send message on socket.

    • socket - Socket instance returned from socket_create()
    • message - Message to send
    • callback - Function to call with message returned as a response (message)
  • uuid() - Create a UUID

API codegen

Refer to instructions in codegen.

Generate Docs

API docs are generated with Ldoc and deployed to GitHub pages.

When changing the API comments, rerun Ldoc and commit the changes in docs/*.

Note: Comments for nakama/nakama.lua must be made in codegen/main.go.

To run Ldoc:

# in the project root, generate nakama.lua
# requires go and https://github.com/heroiclabs/nakama to be checked out
go run codegen/main.go -output nakama/nakama.lua ../nakama/apigrpc/apigrpc.swagger.json

# install ldoc (mac)
brew install luarocks
luarocks install ldoc

# run ldoc
doc . -d docs

Unit tests

Unit tests can be found in the tests folder. Run them using Telescope (fork which supports Lua 5.3+):

./tsc -f test/test_client.lua test/test_socket.lua test/test_session.lua

Contribute

The development roadmap is managed as GitHub issues and pull requests are welcome. If you're interested to enhance the code please open an issue to discuss the changes or drop in and discuss it in the community forum.

License

This project is licensed under the Apache-2 License.