hession RMI 远程调用


/**
*
* @author administror
* 在java中,需要去extends 继承java.rmi.Remote 接口,才能称为在于服务器流的远程对象。
* 各客服端调用
*
*/
public interface Hello extends Remote {
//实现了Remote接口,该接口的方法可以被客服端远程调用

public String helloWord() throws java.rmi.RemoteException;

public String sayGoodBy() throws java.rmi.RemoteException;

}

 


//远程调用对象必须继承java.rmi.server.UniCaseRemoteObject
//这样才能保证我们的远程调用对象在被调用时会把自身的对象进行拷贝并且以socket形式传输给客服端
public class HelloImpl extends UnicastRemoteObject implements Hello {

/**
* 序列化ID
*/
private static final long serialVersionUID = 1L;

/**
* 该构造方法必须实现
* @throws RemoteException
*/
protected HelloImpl() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}

public String helloWord() throws RemoteException {
System.out.println("你好,这里是远程服务中心!");
return "另一车轨迹";
}

public String sayGoodBy() throws RemoteException {
System.out.println("ByeBye 这里是远程服务中心");
return "倩宁";
}

}

 

 


/**
* 远程服务
* @author administror
*
*/
public class Server {

public static void main(String[] args) {

Hello hello;
try {
hello = new HelloImpl(); //生成了stubs skeleton 并且返回了stubs的代理应用
LocateRegistry.createRegistry(8080);
//将stub应用绑定到注册的服务地址
Naming.bind("rmi://127.0.0.1:8080/sunny", hello);
System.out.println("完成服务注册及绑定");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AlreadyBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

 

 


public class Client {

public static void main(String[] args) {

//远程调用方法与本地方法调用是一样的
try {
Hello hello = (Hello)Naming.lookup("rmi://127.0.0.1:8080/sunny");
hello.helloWord();
hello.sayGoodBy();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

posted @ 2017-08-25 10:49  love郎朗you  阅读(199)  评论(0编辑  收藏  举报