Now we have the library book, we can now build up the RMI library factory that will be the server for the clients to communicate to.
To start with we have to setup the security settings
System.setSecurityManager(new RMISecurityManager()); |
this is because the RMI library factory needs to “listen” on the server to remote clients to connect and due to the Java sandbox we have to make a request to the security manager to be allowed to “listen” for remote clients, without the permission there will be a error.
Remote error :Connection refused to host: 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused |
I shall include the policy file when it comes to running the server/client setup.
now all we need to do is to bind the Book class RMI server and call it the “RemoteBook”, you need this to call with the client because you are basically allowing the server to communicate with the client to the Book that has been created (new Book(“Genuxs book… ) )
Book remoteBook = new Book("Genuxs book to borrow"); Naming.rebind("RemoteBook",remoteBook); |
here is the full RMI Factory code
import java.rmi.*; import java.rmi.server.*; import java.net.*; public class RMIFactory { public RMIFactory() { System.setSecurityManager(new RMISecurityManager()); } public void createRemoteBook() { try { Book remoteBook = new Book("Genuxs book to borrow"); Naming.rebind("RemoteBook",remoteBook); } catch (RemoteException e) { System.out.println("Remote error :"+ e.getMessage()); } catch (MalformedURLException mue) { System.out.println("Remote malformed error :"+mue.getMessage()); } System.out.println("Remote book object has been started"); } public static void main(String[] args) { RMIFactory RMIF = new RMIFactory(); RMIF.createRemoteBook(); } } |
if you save that as RMIFactory.java and next it is the client and running the RMI server and RMI client.