Avri Blog

Blog à l'avricot - Lord Of Castle, java, nosql, Utomia, AvriChat, javascript, Json, Css, Mootools, ajax, php...

Aller au contenu | Aller au menu | Aller à la recherche

Stop Bubble | Start

Mot-clé - jwebsocket

Fil des billets - Fil des commentaires

dimanche, septembre 12 2010

Part 3 : S2C rrpc - Introducing jwebsocket and its RPCPlugin - a step by step tutorial (also for gwt)

How-to-make a S2C call, using the Rrpc Class.
On this exemple, the server will send the time to the client (the client is not asking anything).

Creating the rrpc method on the client side

On the client part, create a setServerTime method

rrpcNs = {
   setServerTime: function (aTime) {
      alert("Server is giving the time"+aTime);
  }
}
lWSC.addGrantedProcedure("setServerTime");

Calling the method from the server

Let's say that you have stored in a List all the client connected to your server in a List named
List<WebSocketConnector>mListOfConnector
. making a rrpc call is that simple:

Rrpc.Call("rrpcNs", "setServerTime").send(System.currentTimeMillis()).to(mListOfConnector) ;

Note that the Rrpc Call builder provide other methods, so you should be able to create any rrpc you want.

Part 2 : C2S rpc - Introducing jwebsocket and its RPCPlugin - a step by step tutorial (also for gwt)

If everything is OK, you now have your jwebsocket up and running as soon as your webapp is started

Create your first C2S (client to server) RPC

Let's make the simplest RPC call : we want the server to return the time.
In your server folder, create a new class named RpcTime wich extends BaseRPCCallable, and create a getTime() method, such as:

package testpanel.server.jwebsocket.rpc;
 
import org.jwebsocket.plugins.rpc.BaseRPCCallable;
 
public class RpcTime extends BaseRPCCallable {
	public static long getTime() {
		return System.currentTimeMillis();
	}
}

that's all !
BaseRPCCallable is the Abstract class for rpc class. It provides advanced method used by the websocket during initialization.
If needed, you can also use a BaseConnectorRPCCallable or implement your own class using the RPCCallable Interface.
Get more information about this classes on part 4

Adding the rights to the users.

Jwebsocket works with Roles and Right.
Every user has a Role, and every Role has Rights.
Calling a rpc method is a right, so you'll have to grant access to your getTime method.
Open the jWebsocket.xml file in your /conf folder and add the following right in the <rights></rights> section:

<right>
			<ns>org.jwebsocket.plugins.rpc</ns>
			<id>testpanel.server.jwebsocket.rpc.RpcTime</id>
			<description>A sample Rpc demo: get the server Time</description>
		</right>

Now you have to add the right to the roles:
In the <roles></roles>tag, add the following right (in the <rights>tag) for the role you want:

<right>org.jwebsocket.plugins.rpc.testpanel.server.jwebsocket.rpc.RpcTime</right>

So now your xml file looks like, for instance:

<rights>
		[.... All other rights....]
		<!-- configuration of rpc plug-in specific rights -->
		<right>
			<ns>org.jwebsocket.plugins.rpc</ns>
			<id>rpc</id>
			<description>Allow Remote Procedure Calls (RPC) to server</description>
		</right>
		<right>
			<ns>org.jwebsocket.plugins.rpc</ns>
			<id>rrpc</id>
			<description>Allow Reverse Remote Procedure Calls (RRPC) to other clients</description>
		</right>
 
		<!-- list all granted methods for RPC -->
		<right>
			<ns>org.jwebsocket.plugins.rpc</ns>
			<id>testpanel.server.jwebsocket.rpc.RpcTime</id>
			<description>A sample Rpc demo: get the server Time</description>
		</right>
	</rights>
       <roles>
                 <role>
			<id>Guest</id>
			<description>Anonymous users (not registered)</description>
			<rights>
				<!-- list of rights for "Guest" role (ns + . + id) -->
				<right>org.jwebsocket.plugins.system.broadcast</right>
				<right>org.jwebsocket.plugins.system.send</right>
				<right>org.jwebsocket.plugins.chat.broadcast</right>
				<right>org.jwebsocket.plugins.rpc.rpc</right>
				<right>org.jwebsocket.plugins.rpc.rrpc</right>
				<right>org.jwebsocket.plugins.rpc.org.jwebsocket.rpc.sample.SampleRPCLibrary.sampleOverloadRPC(int)</right>		
			</rights>
		</role>
		[.... All other roles....]
       </roles>

(you will find more informations about the org.jwebsocket.plugins.rpc.rpc and org.jwebsocket.plugins.rpc.rrpc right in the part4.

Calling the method from the client.

Now, we just have to call the Rpc method from the client:

lWSC = new jws.jWebSocketJSONClient();
 
var getTimeFromServer = function () {
  var lRes = lWSC.rpc(
    "testpanel.server.jwebsocket.rpc.RpcTime",
    "getTime",
     null, //parameter of the called method, here null because we don't have any arguments
      {	 spawnThread: false,
	 OnResponse: function( aToken ) {  
		 if( aToken.code != 0 ) {
			 alert( "RPC Error: " + aToken.msg );
		 } else {
			 var lRes = aToken.result;
		         alert( "server time: " + lRes );
		 }
	  }
     }
  );
}
 
var lRes = lWSC.open( jws.JWS_SERVER_URL;);
getTimeFromServer ();

Done :)

Part 1 - Introducing jwebsocket and its RPCPlugin - a step by step tutorial (also for gwt)

{{jWebSocket is a pure Java/JavaScript high speed bidirectional communication solution for the Web - secure, reliable and fast jWebSocket is provided to you to create innovative HTML5 based streaming and communication applications on the web. HTML5 WebSockets will replace the existing XHR approaches as well as Comet services by a new flexible and ultra high speed bidirectional TCP socket communication technology. jWebSocket is an open source Java and JavaScript implementation of the HTML5 WebSocket protocol with a huge set of extensions.}}

Installing jwebsocket

Download

That says, let's make our very first web application based on Jwebsocket using the RPCPlugin !
You'll need a tomcat server and the last jwebsocket bundle zip.
Install tomcat.
- copy the jWebSocketServer-Bundle.jar file into Tomcat's /lib folder to make it accessible (if you are working on eclipse, don't forget add the bundle.jar to your buildpath)
- copy the jWebSocket.xml configuration file in Tomcat's /conf folder. This file contains all the informations about your server configuration.

Start the server with your application

- now, we need to load the jwebsocket server when your application start. The simplest way is to create a ServletContextListener class, and to add it as a tomcat listener:
Create the following class in your server folder:
(my application is named "testpanel")

package testpanel.server;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.jwebsocket.factory.JWebSocketFactory;
 
/**
 * Web application lifecycle listener.
 * @author aschulze
 */
public class ContextListener implements ServletContextListener {
 
  /**
   * initializes the web application on startup.
   * @param sce
   */
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    // start the jWebSocket server sub system
    JWebSocketFactory.start("");
  }
 
  /**
   * cleans up the web application on termination.
   * @param sce
   */
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    // stop the jWebSocket server sub system
    JWebSocketFactory.stop();
 
  }
 
}

- open your web.xml file, and add the following:

<listener>
        <description>ServletContextListener</description>
        <listener-class>testpanel.server.ContextListener</listener-class>
    </listener>

You can now start the server, everything should be fine !

Special gwt errors

tips for gwt users: If your are using gwt and you get the following error:
java.net.ServerSocket is a restricted class. Please see the Google App Engine developer's guide for more details.
You have to disable the appEngine mode for your project, since App Engin doesn't support java.net.ServerSocket.
If after that you have the following error:
java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.<init>(Ljava/ lang/Object;).....
Remove everything you have in your /lib folder, except gwt-servlet.jar, the jwebsocket bundle.jar and your own jar if you have.
Get more detail about this error here and here