Using RPCs in Unity and AppWarp S2

Note : The following article describes RPCs in context of AppWarp

What is RPC?

RPC(Remote Procedure Call) is a mechanism available in AppWarp S2 which enables developers to call methods that are defined on server directly from the clients. Hence, using RPCs developers can extend the server side by implementing his own methods.

Types of RPCs?

  1. Zone RPC
  2. Room RPC

Zone RPCs are the methods defined in zone adaptor. They are invoked on client side by calling invokeZoneRPC() method whereas Room RPCs are defined in room adaptor and are called through invokeRoomRPC() method on client side.

Why you need RPC?

RPC is a great feature, when it comes to extending the server side code. We provide SDK for all major platforms and try to keep the SDK generic so that it can be adopted in various genre of games. But you may need some specific APIs for your game. You can then define RPCs and extend the APIs. Simply create the methods that you want to perform on server side and invoke them from clients.

For example, we provide getOnlineUsers() to get the list of all online users, but what if you want to get all the users who have been playing for past 1 hour. To do so, you can start counting time when a user joins the game and write a method that returns all such players. You may think of sending this information as chat messages, but then all players will receive that message.

Similar activities like picking a weapon, shooting, etc. can be implemented through RPCs.

Using RPCs in Unity

To use RPCs first you need to define your methods on server side and then you can call them from clients. Your methods can be defined either in zone adaptor or room adaptor. Remember to set their access specifier as public.

Suppose you want to define a method that adds two numbers and returns their sum.

Server Side

1
2
3
4
5
6
public class RPCZoneAdaptor extends BaseZoneAdaptor {    
    public int add(int a, int b)
    {
        return a+b;
    }
}

Or,

1
2
3
4
5
6
public class RPCRoomAdaptor extends BaseRoomAdaptor{
    public int add(int a, int b)
    {
        return a+b;
    }
}

Client Side

On Client Side, first you will need to define onInvokeZoneRPCDone in zone listener and onInvokeRoomRPCDone in room request listener.

1
2
3
4
5
6
7
8
9
10
public class Listener : ZoneRequestListener, RoomRequestListener
{
	public void onInvokeZoneRPCDone(RPCEvent eventObj)
	{
	}
 
	public void onInvokeRoomRPCDone(RPCEvent eventObj)
	{
	}
}

After this simply call the method invokeZoneRPC for invoking the method defined in zone adaptor or invokeRoomRPC for invoking the method defined in room.

For example,

1
WarpClient.GetInstance().invokeZoneRPC(“add”,6,7);

or,

1
WarpClient.GetInstance().invokeRoomRPC(9180385”,“add”,6,7)

Now, you can handle the response in listeners. RPCEvent will contain the return value along with function name, zone key and roomID in case of room RPC.

1
2
3
4
5
6
7
public void onInvokeRoomRPCDone(RPCEvent eventObj)
{
	string ret = eventObj.getReturn();
	string func = eventObj.getFunction();
	string zone = eventObj.getAppKey();
	string room = eventObj.getRoomId();
}

Conclusion

To learn more about AppWarp S2, please visit our dev center here.

twitter Using RPCs in Unity and AppWarp S2facebook Using RPCs in Unity and AppWarp S2google Using RPCs in Unity and AppWarp S2linkedin Using RPCs in Unity and AppWarp S2pinterest Using RPCs in Unity and AppWarp S2reddit Using RPCs in Unity and AppWarp S2stumbleupon Using RPCs in Unity and AppWarp S2tumblr Using RPCs in Unity and AppWarp S2
Follow Us
Facebook twitter linkedin google

Getting started with Backbone.js and Rails

I recently started using Backbone.js with my existing web application and have found it to be extremely useful for keeping all my Javascript front-end code organized. As my application has a complicated user interface, I realized my JavaScript code was getting out of control and was tough to maintain due to lack of structure.

This forced me to look for options with which I could keep my code clean and in a structured way. And I found there are many JS frameworks that attempt to offer similar benefits, like Backbone.js, Ember.js, Angular.js, ExtJs and so on.

However, I decided to go with Backbone because it is one of the most extensively used frameworks in creating application frond-end. It has a very active community and it is also being vastly used in production for a considerable number of big companies like: Trello, Basecamp, DISQUE etc.

In this blog post, I am going to walk you through the steps required to integrate Backbone.js with Rails application.

Steps:

First of all, we need to include Backbone gem in our Rails application. So, open Gemfile and include it.

1
gem 'rails-backbone'

As we have added new gem to Gemfile, make sure to run bundle update to install all dependencies.

$ bundle update

Backbone gem comes with a fancy scaffold generator which will create the required artifacts for your application.

backbone install Getting started with Backbone.js and Rails

This creates the following directory structure under app/assets/javascripts/backbone.

backbone/
routers/ (maps HTML routes to actions)
models/ (maintains state)
templates/ (presents clientside views)
views/ (presents model data in the DOM)

In order to setup initial requirements and name spacing, it also creates a coffee script file as app_name.js.coffee.

app/assets/javascript/backbone/app_name.js.coffee

Create a backbone model and collection inside app/assets/javascripts/backbone/models to be used to communicate with rails backend.

$ rails g backbone:model model_name field_name:datatype

We are almost done.  Now you need to edit the index view as per requirement.

1
2
3
4
$(function() {
    window.router = new Model.Routers.ModelRouter({controller: });
    Backbone.history.start();
});

Now start the server.

$ rails s

Thereafter, browse “localhost:3000/controller” and now you will get a fully functioning backbone app with rails.

For more doubts and questions, do write to us at support@shephertz.com

twitter Getting started with Backbone.js and Railsfacebook Getting started with Backbone.js and Railsgoogle Getting started with Backbone.js and Railslinkedin Getting started with Backbone.js and Railspinterest Getting started with Backbone.js and Railsreddit Getting started with Backbone.js and Railsstumbleupon Getting started with Backbone.js and Railstumblr Getting started with Backbone.js and Rails
Follow Us
Facebook twitter linkedin google

How to use RESTFul Web Services with ‘GRAILS’

Web Service is a way of communication between two applications or electronic devices over the World Wide Web. By using Web Services, your application can publish its function or message to the rest of the world. Basically, Web Services are of two types:

1- Simple Object Access Protocol (SOAP)

2- Representational State Transfer (REST).

Why to use REST (Representational State Transfer)?

REST is a stateless, client-server, cacheable communication protocol that runs on top of the HTTP. Instead of using complex mechanism such as CORBA, RPC or SOAP to connect between machines, REST, a simple and lightweight mechanism, is used to make calls between machines. Like Web Services, a REST service is also Platform-independent, Language-independent, Standard-based (runs on top of HTTP), Firewalls independent. SOAP is an XML based message protocol and you can use it and JSON as per your need. REST does not enforce message format and while accessing RESTful resources with HTTP protocol, the URL of the source serves as the resource identifier and GET, PUT, DELETE and POST are the standard HTTP operations to be performed on that resource.

Steps to configure RESTFul Web Services in your Grails application:

Step-1: Create a Grails application

To use the plugin, first of all we need to create a new Grails application. For that, change the working directory to a location, where you want to create a new Grails application and run the command, which is given below.

1
grails create-app restdemo

Step-2: Installing grails-jaxrs plugin in Grails application 

If your Grails version is 2.2.1 and above, add the plugin dependency declaration to your project’s  ’BuildConfig.groovy’

1
2
3
4
5
grails.project.dependency.resolution = {
    plugins {
        compile ':jaxrs:0.8'
    }
}

If your Grails version is below 2.2.1, go to your project’s root directory and then run

1
grails install-plugin jaxrs

Step-3: Create a resource 

To create a JAX-RS resource in your application, run the command given below from your application root directory.

1
grails create-resource user

The above command will create a UserResource.groovy file under grails-app/resources and a UserResourceTests.groovy file under test/unit. The UserResourceTests.groovy file is a unit test template. The UserResource.groovy file is the generated JAX-RS resource.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package restdemo
 
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
 
@Path('/api/user')
class UserResource {
 
    @GET
    @Produces('text/plain')
    String getUserRepresentation() {
        'Hello User'
    }
 
}

It defines a single method that responds to HTTP GET operations. The HTTP response contains the return value of this method, ‘Hello User’ in this example. The content type of the response (Content-Type header) is text/plain. According to your application design, you can also change the Content-Type as accept or produce to application/json, application/xml, multipart/form-data etc. Now, add more methods (POST, PUT, DELETE) in User resource as given in the code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package restdemo
 
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.Consumes
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.DELETE
 
@Path('/api/user')
class UserResource {
 
    @GET
    @Produces('text/plain')
    String getUserRepresentation() {
        'Hello User'
    }
 
    @POST
    @Consumes(['application/json','application/xml','multipart/form-data'])
    @Produces(['application/json','application/xml'])
    String postUserRepresentation() {
        'Hello POST Method Called'
    }
 
    @PUT
    @Consumes(['application/json','application/xml','multipart/form-data'])
    @Produces(['application/json','application/xml'])
    String putUserRepresentation() {
        'Hello PUT Method Called'
    }
 
    @DELETE
    @Consumes(['application/json','application/xml'])
    @Produces(['application/json','application/xml'])
    String deleteUserRepresentation() {
        'Hello DELETE Method Called'
    }
 
}

Now, you have to add URL mapping dependency declaration to your project’s  ’Config.groovy’  and later the created resource will be ready to use as shown in the next section.

1
org.grails.jaxrs.url.mappings=['/api']

Step-4: Run your grails application

Run this command on the command line.

1
grails run-app

Then, open a browser window or poster and go to http://localhost:8080/restdemo/api/user. The browser should now display “Hello User” as shown below.

How to use RESTFul Web Services with GRAILS How to use RESTFul Web Services with GRAILS

In this blog, I have explained you about the Integration of REST Web Services with your Grails Application.

If you have questions or need any further assistance, do write us at support@shephertz.com

twitter How to use RESTFul Web Services with GRAILSfacebook How to use RESTFul Web Services with GRAILSgoogle How to use RESTFul Web Services with GRAILSlinkedin How to use RESTFul Web Services with GRAILSpinterest How to use RESTFul Web Services with GRAILSreddit How to use RESTFul Web Services with GRAILSstumbleupon How to use RESTFul Web Services with GRAILStumblr How to use RESTFul Web Services with GRAILS
Follow Us
Facebook twitter linkedin google

Saving Additional Data and Displaying App42 Leaderboard

What would you do to  fetch the leader board with additional profile information of user like first name, display name, age, country etc?
Well, App42 Gaming APIs come truly handy, when we talk about saving the score and displaying the leader-board in much lesser time. Many developer asked questions while integrating leader board about saving additional data and fetching back in the leader board. Earlier if you wanted to do this, you have to make additional calls to storage service to save and fetch back these information, however we have now introduced a better way of doing it without making any additional call to storage service. Below example is explained using C# Unity code however can be done in similar way for other platform too.

Saving additional data of user’s profile

If you want to save the information on profile like name, age & country and display it on the leader board, you must save the information first on Storage Service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
App42API.SetLoggedInUser(userName);  //Logged in user in your app
StorageService storageService = App42API.BuildStorageService();
storageService.InsertJSONDocument(“YOUR_DBNAME”, "PROFILE_COLLECTION", 
"{\"displayName\":\”UserDisplayName\”,\"Country\":\"US\",}", new UnityCallBack());
 //This will save his profile info
public class UnityCallBack : App42CallBack
{
	public void OnSuccess(object response)
	{
                App42Log.Console("Profile Saved :  " + response);
        }
	public void OnException(Exception e)
	{
                App42Log.Console("Exception : " + e);
	}
}

Fetching addtional info in leaderboard

Once your user profile is saved, you can easily fetch the information while retrieving the leaderbaord and the user’s score as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
ScoreBoardService scoreBoardService= App42API.BuildScoreBoardService();
App42API.SetDbName("YOUR_DBNAME");
Query query= null; // Pass query if you want to get only selected records, null if you want all JSON objects of user
scoreBoardService.SetQuery("PROFILE_COLLECTION", query);
int maxResults = 20;
scoreBoardService.GetTopNRankers(gameName, maxResults, new UnityCallBack() );
public class UnityCallBack : App42CallBack
{
   public void OnSuccess(object response)
   {
       Game game = (Game) response;     
       for (int i = 0; i < getTopRanker.GetScoreList().Count; i++)
       {
            Console.WriteLine("userName is : " + getTopRanker.GetScoreList()[i].GetUserName());
            Console.WriteLine("score is : " + getTopRanker.GetScoreList()[i].GetValue());
            for (int j = 0; j < getTopRanker.GetScoreList()[i].GetJsonDocList().Count; j++)
            {
                 // Following will return JSON Object saved for user and will have his profile info
                 Console.WriteLine("get json doc  = " + getTopRanker.GetScoreList()[i].GetJsonDocList()[j].GetJsonDoc());
             }
         }
    }
    public void OnException(Exception e)
    {
         App42Log.Console("Exception : " + e);
    }
}

If you need further information on ‘Saving Score & Fetching the Leaderboard’, do view our tutorial .

twitter Saving Additional Data and Displaying App42 Leaderboardfacebook Saving Additional Data and Displaying App42 Leaderboardgoogle Saving Additional Data and Displaying App42 Leaderboardlinkedin Saving Additional Data and Displaying App42 Leaderboardpinterest Saving Additional Data and Displaying App42 Leaderboardreddit Saving Additional Data and Displaying App42 Leaderboardstumbleupon Saving Additional Data and Displaying App42 Leaderboardtumblr Saving Additional Data and Displaying App42 Leaderboard
Follow Us
Facebook twitter linkedin google