java rmi使用


远程服务调用,可以在client端运行server端的java代码

server

package rmi.demo;

import java.rmi.NoSuchObjectException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class RmiServer {
	public static void main(String[] args) throws Exception {
		System.out.println("server");
		int port = 8090;
		RemoteObject object = new RemoteObjectImpl();
		RemoteObject remoObject = (RemoteObject) UnicastRemoteObject.exportObject(object, 0);  //导入对象,导入RemoteObjectImpl对象会报错 无法转换
		Registry serRegistry = LocateRegistry.createRegistry(port); //启动rmi server
		serRegistry.bind("remoteObject", remoObject);
		
		new Thread(()->{
			try {
				Thread.sleep(10 * 1000);
				UnicastRemoteObject.unexportObject(object, true); //把对象导出,当没有对象时,关闭rmi server端
				System.out.println("rmi close");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchObjectException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}).start();
	}
}

cilent

package rmi.demo;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RmiClient {
	public static void main(String[] args) throws Exception {
		System.out.println("client");
		
		Registry registry = LocateRegistry.getRegistry("127.0.0.1",8090); //获取远程rmi server
		RemoteObject remoteObject = (RemoteObject) registry.lookup("remoteObject"); //获取对象
		remoteObject.run(); //调用远程的对象
	}
}

object

package rmi.demo;

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

public interface RemoteObject extends Remote{
	void run() throws RemoteException;
}

package rmi.demo;

import java.rmi.RemoteException;

public class RemoteObjectImpl implements RemoteObject{

	@Override
	public void run() throws RemoteException {
		System.out.println("RemoteObjectImpl");
	}
}

运行结果

server

在这里插入图片描述

client

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值