欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java RMI和Java Security,

来源: javaer 分享于  点击 22359 次 点评:46

Java RMI和Java Security,


也是看书才突然想到RMI,RMI的实现网上例子一堆一堆的,我这里主要着重研究的是两者的结合。

看到一个图来描述RMI原理和结构:

所以对于RMI的例子,也就是这样考虑:

一个消息接口,用于可改写任意想要封装的消息HelloRemote,当然也有它的实现.

一个Client.

一个Server.

HelloRemote接口:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloRemote extends Remote {

	public void sayHello() throws RemoteException;   
}
实现类:

/****
 * 远程接口实现类
 */
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloImpl extends UnicastRemoteObject implements HelloRemote {

	private static final long serialVersionUID = 839071482031464015L;

	protected HelloImpl() throws RemoteException {
		super();
	}

	@Override
	public void sayHello() throws RemoteException {

		System.out.println("Hello World!");
	}

}
Client类:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

public class RMIClient {

	public static void main(String args[]) throws MalformedURLException, RemoteException, NotBoundException{
        System.setSecurityManager(new RMISecurityManager());//如果服务器和客户端不再同一台机器要加这行
		HelloRemote hello=(HelloRemote) Naming.lookup("hello");
		hello.sayHello();
	}
}

Server类:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
/****
 * 远程服务端类
 * @author SAMSUNG
 *
 */
public class RMIServer {

	public static void main(String[] args) throws RemoteException, MalformedURLException {
		 if (System.getSecurityManager() == null) {  
               System.setSecurityManager(new RMISecurityManager());   
           }  
		HelloRemote hello=new HelloImpl();
		Naming.rebind("hello", hello);
	}
}
控制台来运行这些代码:

javac *.java

再rmic HelloImpl运行生成存根文件,将其分别放置于client和server包下。

因为开启了Java Security安全管理,所以建立一个policy.txt文件.

grant {
           permission java.net.SocketPermission "*:1024-65535",
                "connect,accept";
           permission java.net.SocketPermission "*:80","connect";
        };
运行如下:

D:/RMI/server>java -Djava.security.policy=policy.txt RMIServer

D:/RMI/client>java -Djava.security.policy=policy.txt RMIClient

当然了这是一种System安全管理,还有一种我们可以这样:

   AccessController.doPrivileged( new  PrivilegedAction()  {  
            public  Object run()  {  
                sayHello();  
                return   null ;  
            }  
        }


相关文章

    暂无相关文章
相关栏目:

用户点评