Java Services: How To

There are few simple steps in creating a Java Services server/client.

Step 1: Define and compile the interface

The first step is to define an interface - the contract between the provider and the client.

Let us use the following simple interface (with a single method for simplicity):


public interface Reverse { 
    public String reverseString( String str ); 
} 

Compile this file and make sure it is available in the Java Services classpath.

Step 2: Register the interface

Java Services needs to be told about the interface. This is done by the command

jsregintf Reverse

This command should output a message saying the registration was successful.

Step 3: Writing the provider

Now we have to write and compile a "provider" class, i.e. a class that implements this interface.

public class MyProvider implements Reverse {
    public String reverseString( String str )
    {
        StringBuffer rev = new StringBuffer();
        for ( int i = str.length()-1; i > 0; i-- )
            rev.append( str.charAt( i ));
        return rev.toString();
        
    }
}

Step 4: Registering the provider

The provider class needs to be registered as well.

jsregprovider MyProvider Reverse

Which is telling JavaServices that "MyProvider" class will provide the interface "Reverse".

Step 5: Writing the client

The client must have the "Reverse.class" available, and in it's classpath. The client must also have the JSVCSclient.jar file in its classpath.

If the classpath is setup correctly, the client simply looks up the "Reverse" interface using the hostname/IP-address, and the port number, of the server.


public class SomeClient { 
  public static void main( String[] args ) 
  {
    try { 
      // Get an instance of Java Services

      JSVCS jsvc = new JSVCS(); 

      // Lookup if there is a "Reverse" interface registered at a given host

      Reverse r = (Reverse) jsvc.lookup( "JavaServiceHost.com", 4444, Reverse.class );

      // That's it.  Use the interface.

      String reversed = r.reverseString( "A String" ); 
      System.out.println( "Reversed = " + reversed );

    } catch (Exception ex) { 
      ex.printStackTrace(); 
    }
  } 
} 
 
It is as simple as that! As long as the interface "Reverse" is registered with JSVCS running at JavaServiceHost.com at port 4444, the above client will be able to use the interface to make remote calls over the web.

Note that the client does not need to know anything about "MyProvider". The provider class can change, or be replaced, and client will continue to work as expected.

Step 6: Callbacks

In addition to providing results of method calls, the provider can also make callbacks to the client. This is described in more detail in the JSVC documentation.