温故而知新可以为师矣
1.远程接口
package com.example.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IService extends Remote {
String sayHello() throws RemoteException;
String sayHello(String name) throws RemoteException;
HelloImpl.User getUser() throws RemoteException;
}
2.远程接口实现类
package com.example.rmi;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements IService {
public HelloImpl() throws RemoteException {
}
@Override public String sayHello() {
return "hello bruce.";
}
@Override public String sayHello(String name) {
return name;
}
@Override public User getUser() throws RemoteException {
return new User("bruce",30);
}
public static class User implements Serializable{
public String name;
public int age;
public User(String name, int i) {
this.name= name;
this.age= i;
}
public String toString(){
return this.name+":"+this.age;
}
}
}
3.注册远程服务接口
package com.example.rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class Server {
public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException {
IService service= new HelloImpl();
LocateRegistry.createRegistry(8888);
Naming.bind("rmi://localhost:8888/r_hello",service);
}
}
4.远程客户端调用
package com.example.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class Client {
public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
IService iService= (IService) Naming.lookup("rmi://localhost:8888/r_hello");
System.out.println(iService.sayHello());
System.out.println(iService.sayHello("成功啦"));
HelloImpl.User user= iService.getUser();
System.out.println((user));
}
}
网友评论