Service Interface
// This is the interface that the service's proxy
// implements
package corejini.chapter5;
Service
// This is a Hello, World
// service--it publishes a proxy that returns
// a string when asked by clients.
package corejini.chapter5;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;
import net.jini.discovery.LookupDiscovery;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceRegistration;
import java.util.Hashtable;
import java.io.IOException;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
1
return "Hello, world!";
}
}
// Install a listener.
disco.addDiscoveryListener(new Listener());
}
2
}
try {
registration = registrar.register(item, LEASE_TIME);
} catch (RemoteException ex) {
System.out.println("Couldn't register: " +
ex.getMessage());
return;
}
registrations.put(registrar, registration);
}
3
Client
package corejini.chapter5;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;
import net.jini.discovery.LookupDiscovery;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import java.util.Vector;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
// Install a listener
disco.addDiscoveryListener(new Listener());
}
4
try {
o = lusvc.lookup(template);
} catch (RemoteException ex) {
System.err.println("Error doing lookup: " +
ex.getMessage());
return null;
}
if (o == null) {
System.err.println("No matching service.");
return null;
}
return o;
}
5
Compile and Deploy
You need to download Jini from Sunsoft for this example to work. While compiling the
code for the Service and Client, include the appropriate Jini JAR files in the
CLASSPATH.
When deploying the service and client on different machines, keep in mind that for the
service the following classes need to be compiled:
HelloWorldServiceInterface.java
HelloWorldServiceProxy.java
HelloWorldService.java
HelloWorldServiceInterface.java
HelloWorldClient.java
Note that the client does not need HelloWorldServiceProxy.java at compile time,
since the byte code HelloWorldServiceProxy.class is not needed on the
client’s machine, when the client is started. The code,
HelloWorldServiceProxy.class, will automatically be downloaded, along with
the proxy object, when the client requests the service from a lookup service.
To keep this example simple, the service needs to be started before the client. Notice
however, that the service has been implemented in such a way that it can be started
before or after a lookup servide. If the service can not find a lookup, then it simply waits
until a lookup service joins the community, at which time the service registers itself with
the lookup, and sends it its proxy object.