The official cocos2d JavaScript client handles all communication in real-time with the server. It implements all features in the server and can be used in cocos2d-x js projects. The client also comes with type definitions so it can be used via TypeScript.
The JavaScript client is open source on GitHub. Please report issues and contribute code to help us improve it.
The client object is used to execute all logic against the server:
1
2
3
4
5
6
7
8
9
10
// Default connection settings for a local Nakama server
varserverkey="defaultkey";varhost="127.0.0.1";varport="7350";varuseSSL=false;vartimeout=7000;// ms
varclient=newnakamajs.Client(serverkey,host,port,useSSL,timeout);varclient=newnakamajs.Client();
Cocos2d does not support await and promises JavaScript features. You have to use promises which are provided by polyfill third party library.
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.
By default Nakama will try to create a user if it doesn’t exist.
Use the following code to store the session:
1
2
3
4
5
6
7
8
9
10
11
constemail="hello@example.com";constpassword="somesupersecretpassword";client.authenticateEmail(email,password).then(function(session){cc.log("Authenticated successfully. User id:",session.user_id);// Store session token for quick reconnects.
cc.sys.localStorage.setItem("nakamaToken",session.token);},function(error){cc.error("authenticate failed:",JSON.stringify(error));});
In the code above we use authenticateEmail but for other authentication options have a look at the code examples.
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.
The server also provides a storage engine to keep save games and other records owned by users. We’ll use storage to introduce how messages are sent.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
constobjects=[{"collection":"collection","key":"key1","value":{"jsonKey":"jsonValue"}},{"collection":"collection","key":"key2","value":{"jsonKey":"jsonValue"}}];client.writeStorageObjects(session,objects).then(function(storageWriteAck){cc.log("Storage write was successful:",JSON.stringify(storageWriteAck));},function(error){cc.error("Storage write failed:",JSON.stringify(error));});
Have a look at other sections of documentation for more code examples.
You first need to create a real-time socket to the server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
constuseSSL=false;constverboseLogging=false;constcreateStatus=false;// set `true` to send presence events to subscribed users.
constsocket=client.createSocket(useSSL,verboseLogging);varsession="";// obtained by authentication.
socket.connect(session,createStatus).then(function(){cc.log("connected");},function(error){cc.error("connect failed:",JSON.stringify(error));});
Then proceed to join a chat channel and send a message:
socket.onchannelmessage=function(channelMessage){cc.log("Received chat message:",JSON.stringify(channelMessage));};constchannelId="pineapple-pizza-lovers-room";constpersistence=false;consthidden=false;socket.joinChat(channelId,1,persistence,hidden).then(function(response){cc.log("Successfully joined channel:",response.channel.id);sendChatMessage(response.channel.id);},function(error){cc.error("join channel failed:",JSON.stringify(error));});functionsendChatMessage(channelId){socket.writeChatMessage(channelId,{"message":"Pineapple doesn't belong on a pizza!"}).then(function(messageAck){cc.log("Successfully sent chat message:",JSON.stringify(messageAck));},function(error){cc.error("send message failed:",JSON.stringify(error));});}
You can find more information about the various chat features available here.
socket.ondisconnect=function(event){cc.log("Disconnected from the server. Event:",JSON.stringify(event));};socket.onnotification=function(notification){cc.log("Received notification:",JSON.stringify(notification));};socket.onchannelpresence=function(presence){cc.log("Received presence update:",JSON.stringify(presence));};socket.onchannelmessage=function(message){cc.log("Received new chat message:",JSON.stringify(message));};socket.onmatchdata=function(matchdata){cc.log("Received match data: ",JSON.stringify(matchdata));};socket.onmatchpresence=function(matchpresence){cc.log("Received match presence update:",JSON.stringify(matchpresence));};socket.onmatchmakermatched=function(matchmakerMatched){cc.log("Received matchmaker update:",JSON.stringify(matchmakerMatched));};socket.onstatuspresence=function(statusPresence){cc.log("Received status presence update:",JSON.stringify(statusPresence));};socket.onstreampresence=function(streamPresence){cc.log("Received stream presence update:",JSON.stringify(streamPresence));};socket.onstreamdata=function(streamdata){cc.log("Received stream data:",JSON.stringify(streamdata));};
Some events only need to be implemented for the features you want to use.
Callbacks
Description
onDisconnect
Received when the client is disconnected from the server.
The server and the client can generate logs which are helpful to debug code. To log all messages sent by the client you can enable verbose when you build a client.
varclient=newnakamajs.Client("defaultkey");varcurrentSession=null;functionstoreSession(session){cc.sys.localStorage.setItem("nakamaToken",session.token);cc.log("Session stored.");}functiongetSessionFromStorage(){returncc.sys.localStorage.getItem("nakamaToken");}functionrestoreSessionOrAuthenticate(){constemail="hello@example.com";constpassword="somesupersecretpassword";varsession=null;try{varsessionString=getSessionFromStorage();if(sessionString&&sessionString!==""){session=nakamajs.Session.restore(sessionString);varcurrentTimeInSec=newDate()/1000;if(!session.isexpired(currentTimeInSec)){cc.log("Restored session. User ID: ",session.user_id);returnPromise.resolve(session);}}returnnewPromise(function(resolve,reject){client.authenticateEmail(email,password).then(function(session){storeSession(session);cc.log("Authenticated successfully. User ID:",session.user_id);resolve(session);},function(error){cc.error("authenticate failed:",JSON.stringify(error));reject(error);});});}catch(e){cc.log("An error occurred while trying to restore session or authenticate user:",JSON.stringify(e));returnPromise.reject(e);}}restoreSessionOrAuthenticate().then(function(session){currentSession=session;returnclient.writeStorageObjects(currentSession,[{"collection":"collection","key":"key1","value":{"jsonKey":"jsonValue"}}]);}).then(function(writeAck){cc.log("Storage write was successful - ack:",JSON.stringify(writeAck));}).catch(function(e){cc.log("An error occurred:",JSON.stringify(e));});