Cocos2d-x C++ client guide

The official C++ client handles all communication in realtime with the server. It implements all features in the server and is written with C++11.


The client SDK can be downloaded from GitHub releases. You can download "nakama-cocos2d-x-sdk_$".

For upgrades you can see changes and enhancements in the CHANGELOG before you update to newer versions.

Help and contribute

The Cocos2d-x C++ client is open source on GitHub. Please report issues and contribute code to help us improve it.


When you've downloaded the Nakama C++ archive and extracted it to NAKAMA_COCOS2D_SDK folder, you should include it in your project.

We don't recommend to copy Nakama C++ SDK to your project because it's quite big in size (~1 Gb).

Copy NakamaCocos2d folder

Copy NakamaCocos2d folder from NAKAMA_COCOS2D_SDK to your Classes folder.

Add all files from NakamaCocos2d folder to your project.

Setup for Mac and iOS projects

  1. Add NAKAMA_COCOS2D_SDK/include in Build Settings > Header Search Paths
  2. Add libs folder in Build Settings > Library Search Paths:
    • NAKAMA_COCOS2D_SDK/libs/ios - for iOS
    • NAKAMA_COCOS2D_SDK/libs/mac - for Mac
  3. Add all .a files located in libs folder and libresolv.9.tbd in General > Linked Frameworks and Libraries

Setup for Android projects

If you use CMake then see Setup for CMake projects section.

If you use ndk-build then add following to your file:

# add this to your module

# add this at bottom of file
$(call import-add-path, NAKAMA_COCOS2D_SDK)
$(call import-module, nakama-cpp-android)

Android uses a permissions system which determines which platform services the application will request to use and ask permission for from the user. The client uses the network to communicate with the server so you must add the "INTERNET" permission.

<uses-permission android:name="android.permission.INTERNET"/>

Setup for CMake projects

Add following to your CMakeLists.txt file:

add_subdirectory(NAKAMA_COCOS2D_SDK ${CMAKE_CURRENT_BINARY_DIR}/nakama-cpp)
target_link_libraries(${APP_NAME} ext_nakama-cpp)

Setup for Visual Studio projects

In Project Settings add following:

  1. Add NAKAMA_COCOS2D_SDK/include in C/C++ > General > Additional Include Directories
  2. Add libs folder in Linker > General > Additional Library Directories:
    • NAKAMA_COCOS2D_SDK/libs/win32/v140 - for VS 2015 x86
    • NAKAMA_COCOS2D_SDK/libs/win32/v141 - for VS 2017 x86
    • NAKAMA_COCOS2D_SDK/libs/win64/v140 - for VS 2015 x64
    • NAKAMA_COCOS2D_SDK/libs/win64/v141 - for VS 2017 x64
  3. Add all .lib files located in libs folder in Linker > Input > Additional Dependencies


Include nakama header.

#include "nakama-cpp/Nakama.h"

Use nakama namespace.

using namespace Nakama;

The client object is used to execute all logic against the server.

DefaultClientParameters parameters;
parameters.serverKey = "defaultkey"; = "";
parameters.port = 7349;
NClientPtr client = createDefaultClient(parameters);


By default the client uses connection settings "" and 7349 port to connect to a local Nakama server.

// Quickly setup a client for a local server.
NClientPtr client = createDefaultClient(DefaultClientParameters());


The tick method pumps requests queue and executes callbacks in your thread. You must call it periodically (recommended every 50ms) in your thread.

auto tickCallback = [this](float dt)
    if (rtClient)

auto scheduler = Director::getInstance()->getScheduler();
scheduler->schedule(tickCallback, this, 0.05f /*sec*/, CC_REPEAT_FOREVER, 0, false, "nakama-tick");

Without this the default client and realtime client will not work, and you will not receive responses from the server.


With a client object you can authenticate against the server. You can register or login a user with one of the authenticate options.

To authenticate you should follow our recommended pattern in your client code:

   1. Build an instance of the client.

NClientPtr client = createDefaultClient(DefaultClientParameters());

   2. Authenticate a user. By default Nakama will try and create a user if it doesn't exist.


It's good practice to cache a device identifier on Android when it's used to authenticate because they can change with device OS updates.

auto loginFailedCallback = [](const NError& error)

auto loginSucceededCallback = [](NSessionPtr session)

std::string deviceId = "unique device id";


In the code above we use authenticateDevice() but for other authentication options have a look at the code examples.


When authenticated the server responds with an auth token (JWT) which contains useful properties and gets deserialized into a NSession object.

CCLOG("%s", session->getAuthToken().c_str()); // raw JWT token
CCLOG("%s", session->getUserId().c_str());
CCLOG("%s", session->getUsername().c_str());
CCLOG("Session has expired: %s", session->isExpired() ? "yes" : "no");
CCLOG("Session expires at: %llu", session->getExpireTime());
CCLOG("Session created at: %llu", session->getCreateTime());

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. The expiry time of the token can be changed as a setting in the server.

A full example class with all code above is here.

Send requests

When a user has been authenticated a session is used to connect with the server. You can then send messages for all the different features in the server.

This could be to add friends, join groups, or submit scores in leaderboards. You can also execute remote code on the server via RPC.

All requests are sent with a session object which authorizes the client.

auto successCallback = [](const NAccount& account)
    CCLOG("user id : %s",;
    CCLOG("username: %s", account.user.username.c_str());
    CCLOG("wallet  : %s", account.wallet.c_str());

client->getAccount(session, successCallback, errorCallback);

Have a look at other sections of documentation for more code examples.

Realtime client

The client can create one or more realtime clients. Each realtime client can have it's own event listener registered for responses received from the server.


The socket is exposed on a different port on the server to the client. You'll need to specify a different port here to ensure that connection is established successfully.

#include "NakamaCocos2d/NWebSocket.h"

int port = 7350; // different port to the main API port
bool createStatus = true; // if the server should show the user as online to others.
// define realtime client in your class as NRtClientPtr rtClient;
rtClient = client->createRtClient(port, NRtTransportPtr(new NWebSocket()));
// define listener in your class as NRtDefaultClientListener listener;
    CCLOG("Socket connected");
rtClient->connect(session, createStatus);

Don't forget to call tick method. See Tick section for details.

You can use realtime client to send and receive chat messages, get notifications, and matchmake into a multiplayer match. You can also execute remote code on the server via RPC.

To join a chat channel and receive messages:

listener.setChannelMessageCallback([](const NChannelMessage& message)
    CCLOG("Received a message on channel %s", message.channel_id.c_str());
    CCLOG("Message content: %s", message.content.c_str());

std::string roomName = "Heroes";

auto successJoinCallback = [this](NChannelPtr channel)
    CCLOG("joined chat: %s", channel->id.c_str());

    // content must be JSON
    std::string content = "{\"message\":\"Hello world\"}";

    rtClient->writeChatMessage(channel->id, content);


There are more examples for chat channels here.

Handle events

A realtime client has event handlers which are called on various messages received from the server.

listener.setStatusPresenceCallback([](const NStatusPresenceEvent& event)
    for (auto& presence : event.joins)
        CCLOG("Joined User ID: %s Username: %s Status: %s", presence.user_id.c_str(), presence.username.c_str(), presence.status.c_str());

    for (auto& presence : event.leaves)
        CCLOG("Left User ID: %s Username: %s Status: %s", presence.user_id.c_str(), presence.username.c_str(), presence.status.c_str());

Event handlers only need to be implemented for the features you want to use.

Callbacks Description
onDisconnect Handles an event for when the client is disconnected from the server.
onNotification Receives live in-app notifications sent from the server.
onChannelMessage Receives realtime chat messages sent by other users.
onChannelPresence It handles join and leave events within chat.
onMatchState Receives realtime multiplayer match data.
onMatchPresence It handles join and leave events within realtime multiplayer.
onMatchmakerMatched Received when the matchmaker has found a suitable match.
onStatusPresence It handles status updates when subscribed to a user status feed.
onStreamPresence Receives stream join and leave event.
onStreamState Receives stream data sent by the server.


Client logging is off by default.

To enable logs output to console with debug logging level:

#include "NakamaCocos2d/NCocosLogSink.h"

NLogger::init(std::make_shared<NCocosLogSink>(), NLogLevel::Debug);


The server and the client can generate logs which are helpful to debug code.

To enable client logs see Logging section.

In every request in the client you can set error callback. It will be called when request fails. The callback has NError structure which contains details of the error:

auto errorCallback = [](const NError& error)
    // convert error to readable string
    CCLOGERROR("%s", toString(error).c_str());

    // check error code
    if (error.code == ErrorCode::ConnectionError)
        CCLOG("The server is currently unavailable. Check internet connection.");

client->getAccount(session, successCallback, errorCallback);

The client writes all errors to logger so you don't need to do this.

Full Cocos2d-x C++ example

You can find the Cocos2d-x C++ example here

Client reference

You can find the C++ Client Reference here.