Sending data stored in ArrayList via RMI
1 answer
Define an interface for server and client (same package name)
package arrayListRMI;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
public interface IArrayList extends Remote {
public ArrayList<String> getText() throws RemoteException;
public void setText(ArrayList<String> text) throws RemoteException;
}
Define the utility class Constants.java
package arrayListRMI;
public class Constants {
public static final String RMI_ID = "StackOverflowAnswer";
public static final int RMI_PORT = 222 ;
}
Add an implementation for IArrayList
(server side)
package arrayListRMI;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class ArrayListImpl extends UnicastRemoteObject implements IArrayList{
private static final long serialVersionUID = 1L;
private ArrayList<String> text;
protected ArrayListImpl() throws RemoteException {
super();
}
public ArrayList<String> getText() {
return text;
}
public void setText(ArrayList<String> text) {
this.text = text;
}
}
So you can instantiate ArrayList
String
(text) on the server side by instantiating ArrayListImpl
and bind to rmiregistry
so the client can request it at any time.
ArrayList<String> textRequested = new ArrayList<String>();
textRequested.add("example1");
textRequested.add("example2");
ArrayListImpl arrayListToSend = new ArrayListImpl();
arrayListToSend.setText(textRequested);
Server
package arrayListRMI;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.SQLException;
public class Server {
public static void main(String args[]) throws AlreadyBoundException, SQLException, ClassNotFoundException {
try {
ArrayList<String> textRequested = new ArrayList<String>();
textRequested.add("example1");
textRequested.add("example2");
ArrayListImpl arrayListToSend = new ArrayListImpl();
arrayListToSend.setText(textRequested);
Registry registry = LocateRegistry.createRegistry(Constants.RMI_PORT);
registry.bind(Constants.RMI_ID, arrayListToSend);
System.out.println("Server starts....");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Client
package arrayListRMI;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", Constants.RMI_PORT);
IArrayList cmp = (IArrayList) registry.lookup(Constants.RMI_ID);
ArrayList<String> received = cmp.getText();
System.out.println(received);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Now start the server. You get this result
Server starts....
Then start the client. You get this result
[example1, example2]
+2
source to share