Пример Java RMI Hello World

Пример Java RMI Hello World

RMI означаетRemote Method Invocation и является объектно-ориентированным эквивалентом RPC (удаленных вызовов процедур). RMI was designed to make the interaction between applications using the object-oriented model and run on different machines seem like that of stand-alone programs.

Приведенный ниже код даст вам основу для Java RMI с очень простым примером модели взаимодействия сервер-клиент.

1. Удаленный интерфейс

Первое, что нам нужно спроектировать, - это интерфейсRemote, который будут реализовывать и сервер, и клиент. Interface всегда должен быть открытым и расширятьRemote. Все методы, описанные в интерфейсеRemote, должны указыватьRemoteException в своем предложении throws.

У нашегоRMIInterface есть только один метод; он получает параметр String и возвращает String.

RMIInterface.java

package com.techfou.rmiinterface;

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

public interface RMIInterface extends Remote {

    public String helloTo(String name) throws RemoteException;

}

2. Сервер

Наш Сервер расширяетUnicastRemoteObject и реализуетInterface, которые мы сделали ранее. В основном методе мы привязываем сервер на localhost с именем MyServer.

ServerOperation.java

package com.techfou.rmiserver;

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

import com.example.rmiinterface.RMIInterface;

public class ServerOperation extends UnicastRemoteObject implements RMIInterface{

    private static final long serialVersionUID = 1L;

    protected ServerOperation() throws RemoteException {

        super();

    }

    @Override
    public String helloTo(String name) throws RemoteException{

        System.err.println(name + " is trying to contact!");
        return "Server says hello to " + name;

    }

    public static void main(String[] args){

        try {

            Naming.rebind("//localhost/MyServer", new ServerOperation());
            System.err.println("Server ready");

        } catch (Exception e) {

            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();

        }

    }

}

3. Клиент

Наконец, мы создаем клиента. Чтобы «найти» Сервер, Клиент использует объектRMIInterface, который «ищет» ссылку на удаленный объект, связанный с именем, которое мы передаем в качестве параметра. С этим объектомRMIInterface теперь мы можем разговаривать с Сервером и получать ответы.

Файл: ClientOperation.java

package com.example.rmiclient;

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

import javax.swing.JOptionPane;

import com.example.rmiinterface.RMIInterface;

public class ClientOperation {

    private static RMIInterface look_up;

    public static void main(String[] args)
        throws MalformedURLException, RemoteException, NotBoundException {

        look_up = (RMIInterface) Naming.lookup("//localhost/MyServer");
        String txt = JOptionPane.showInputDialog("What is your name?");

        String response = look_up.helloTo(txt);
        JOptionPane.showMessageDialog(null, response);

    }

}

4. Как запустить это

4.1 Create the three java files with your favorite IDE or Download the code below. Перейдите в исходную папку, как показано ниже.

java-rmi-hello-9a

4.2 First thing we need to do is compile our sources. ЗапуститеcompileEverything.bat, если вы загрузили код ниже, или откройте командное окно в своем каталоге и запустите:

Терминал

javac src/com/example/rmiinterface/RMIInterface.java src/com/example/rmiserver/ServerOperation.java src/com/example/rmiclient/ClientOperation.java

4.3 Confirm that your sources were compiled by accessing their respective directories:

java-rmi-hello-9b

4.4 Next we need to start the rmiregistry. Снова либо запуститеstartServer.bat, либо откройте командное окно и запустите:

Терминал

cd src
start rmiregistry
java com.example.rmiserver.ServerOperation

java-rmi-hello-9c

4.5 If RmiRegistry started successfully, there will be another window that looks like this:

java-rmi-hello-9d

4.6 Now we are ready to run our Client:

Откройте новое окно командной строки (или запуститеrunClient.bat из загруженных файлов) и запустите это:

Терминал

cd src
java com.example.rmiclient.ClientOperation

ClientOperation запускается и запрашивает ввод:

java-rmi-hello-9e

Мы вводим имя в поле ввода (например, «Марилена») и нажмите «ОК».

4.7 On Server side we can see this:

java-rmi-hello-9f

4.8 And on the Client side this:

java-rmi-hello-9g

4.9 The client closes after the exchange is over, while the server stays on and we can communicate again if we run the client file again. Действительно, запускаем клиент снова и:

java-rmi-hello-9h

Сервер:

java-rmi-hello-9i

Клиент:

java-rmi-hello-9j

Скачать исходный код

Скачать -SimpleRmiExample.zip (4 КБ)