JavaWeb--(02)--rmi分布式计算矩形(圆形)的周长、面积(远程调用方法)

1.编写图中的4个.java类,然后在cmd下编译成.class文件。在根目录下使用命令javac xxx.java即可将.java编译成.class文件
在这里插入图片描述
2.以下是四个类的代码

(1)远程接口类

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

public interface RectangleInterface extends Remote{
	public String Rectangle(double a,double b) throws RemoteException;
}

(2)主类

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RectangleImpl 
	extends UnicastRemoteObject implements RectangleInterface{
	protected RectangleImpl() throws RemoteException{
		super();
	}
	public String Rectangle(double a,double b) throws RemoteException{
		// TODO Auto-generated method stub
		return "Rectangle Perimeter:"+(a+b)*2+'\n'+"Rectangle Area:"+a*b;
	}
}

(3)服务端类

import java.rmi.Naming;
import java.rmi.Remote;

public class RectangleServer {

	private static final Remote rectangle = null;
	
	public static void main(String[] args) {
	
		try {
			RectangleImpl rectangle = new RectangleImpl();
			Naming.bind("rmi://localhost:1099/rectangle_area",rectangle);
			System.out.println("object bound!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

(4)客户端类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Scanner;

public class RectangleClient {
	public static void main(String[] args){
		
			try {
				RectangleInterface cir =(RectangleInterface)Naming.lookup("rmi://172.16.181.23:1099/rectangle_area");		
				System.out.println("请输入长:");
				BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
				double a=Double.parseDouble(br.readLine());
                                                                System.out.println("请输入宽:");
                                                               double b=Double.parseDouble(br.readLine());
                                                               System.out.println(cir.Rectangle(a,b));

			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 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();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
}

3.打开一个cmd定位到文件目录下。
在这里插入图片描述
4.另一部计算机也打开cmd
在这里插入图片描述

发布了28 篇原创文章 · 获赞 6 · 访问量 2874

猜你喜欢

转载自blog.csdn.net/weixin_45621658/article/details/102458094
今日推荐