public class User implements Serializable{
private static final long serialVersionUID = 42L;
String name;
int id;
public User(String name, int id) {
this.name = name;
this.id = id;
}
}
public interface Config {
String url = "rmi://" + Config.SERVER_IP
+ ":" + Config.PORT
+ "/" + Config.OBJECT_NAME;
String OBJECT_NAME = "user";
String SERVER_IP = "localhost";
int PORT = 1099;
}
public interface UserHandler extends Remote{
String getUserName(int id) throws RemoteException;
int getUserCount() throws RemoteException;
User getUserByName(String name) throws RemoteException;
}
public class UserHandlerImpl extends UnicastRemoteObject implements UserHandler{
protected UserHandlerImpl() throws RemoteException {
super();
}
@Override
public String getUserName(int id) throws RemoteException {
return "Tom";
}
@Override
public int getUserCount() throws RemoteException {
return 1;
}
@Override
public User getUserByName(String name) throws RemoteException {
return new User("Tom", 1);
}
}
public class Server {
public Server() {
UserHandler userHandler = null;
Registry registry = null;
try {
System.setProperty("java.rmi.server.hostname",Config.SERVER_IP);
registry = LocateRegistry.createRegistry(Config.PORT);
userHandler = new UserHandlerImpl();
registry.rebind(Config.OBJECT_NAME, userHandler);
System.out.println(" rmi server is ready ...");
} catch (RemoteException e) {
System.out.println(" rmi server is failed ...");
e.printStackTrace();
}
}
}
public class Client {
public Client() {
try {
UserHandler handler = (UserHandler) Naming.lookup(Config.url);
int count = handler.getUserCount();
String name = handler.getUserName(1);
System.out.println("name: " + name);
System.out.println("count: " + count);
System.out.println("user: " + handler.getUserByName("Tom"));
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Server s = new Server();
Client c = new Client();
}
}