I have three java files one is RMI server and RMI client and interface file, as follow: server:
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends
java.rmi.server.UnicastRemoteObject implements ReceiveMessageInterface{
String address;
Registry registry;
public void receiveMessage(String x) throws RemoteException{
System.out.println(x);
}
public RmiServer() throws RemoteException{
try{
address = (InetAddress.getLocalHost()).toString();
}
catch(Exception e){
System.out.println("can't get inet address.");
}
int port=3233;
System.out.println("this address=" + address + ",port=" + port);
try{
registry = LocateRegistry.createRegistry(port);
registry.rebind("rmiServer", this);
}
catch(RemoteException e){
throw e;
}
}
static public void main(String args[]){
try{
RmiServer s = new RmiServer();
}
catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
client:
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient{
static public void main(String args[]){
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println
("sending " + text + " to " +serverAddress + ":" + serverPort);
try{
registry=LocateRegistry.getRegistry
(serverAddress,(new Integer(serverPort)).intValue());
rmiServer=(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}
interface:
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote{
void receiveMessage(String x) throws RemoteException;
}
so basically, when i run the server it will give my laptop address and port that is running in and this is working very well however, the problem is when i run the client after i run the server it keep throwing this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
which client file in where this line:
String serverAddress=args[0];
As there is no argument value passed to the main method that's why it's throwing error.
I believe you are not assigning the command line arguments to the main method. If you are using any IDE to run the project then search how to pass arguments during project execution.
Here you can find how to configure arguments for Netbeans IDE - Netbeans how to set command line arguments in Java
If you are using any other IDE then similarly search for that.
Otherwise, you can simply provide command-line arguments to the program by running via command prompt.