Creating Remote Interface

Listing 6.1 TDInterface.java

import java.rmi.*; 

//Remote interface
public interface TDInterface 
	 extends Remote { 

//This method is used 
//to get the current date and time.
public String getDateAndTime() 
	throws RemoteException; 
}

TDInterface declares a single method that returns the current date and time to the caller.


Server Implementation

Listing 6.2 TDServerImpl.java (Complete server code)

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.rmi.registry.*;
import java.util.*;

//Server implementation
public class TDServerImpl extends UnicastRemoteObject
implements TDInterface {

//constructor
public TDServerImpl() throws RemoteException {
	System.out.println("Creating Server Object");
}

//Remote method used to get current
//date and time.
public String getDateAndTime() {
	String date = "";	 	
	String time = "";
	
	//Get a calendar object using the default 
	//time zone and locale.
	Calendar cal=Calendar.getInstance();
			
	//Get the value for a given time field.
	int day=cal.get(Calendar.DATE);
	int month=cal.get(Calendar.MONTH);
	int year=cal.get(Calendar.YEAR);
	date = "Date: "+day+"/"+month+"/"+year +" ";
			
	int sec=cal.get(Calendar.SECOND);
	int min=cal.get(Calendar.MINUTE);
	int hour=cal.get(Calendar.HOUR);
	time = "Time: "+hour+":"+min+":"+sec;
	return (date + time);
}

//main method 

public static void main(String args[]) { 
  try { 

//Create a server object TDServerImpl obj = new TDServerImpl(); //Create and export a Registry on the //local host that accepts requests on //port number 2000. Registry reg = LocateRegistry.createRegistry(2000); //Rebind the specified name to a remote //object. Any existing binding for the //name will be replaced. reg.rebind("Server",obj); System.out.println("Server ready"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); } } }

Explanation

The getDateAndTime() method creates a Calendar instance to get the current date and time. Finally, it returns the current date and time to the caller. The main method creates a remote object and binds the specified name to that remote object.

 

 

 

RMI BOOK MAIN PAGE                Top

  
Copyright © 2001 www.universalteacher.com