Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีส่งข้อมูลผ่าน Remote Method (RMI) ใน Java

RMI (Remote Method Invocation) ช่วยให้ Object ใน JVM หนึ่ง เรียก Method ของ Object ใน JVM อีกตัวหนึ่ง (Distributed Computing) Package: java.rmi

5 ขั้นตอนสร้าง RMI Application

Step 1: Define Remote Interface

Extends java.rmi.Remote ทุกเมธอดต้อง throws RemoteException

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

public interface Hello extends Remote {
    void printMsg() throws RemoteException;
}

Step 2: Implement Remote Object

public class ImplExample implements Hello {
    public void printMsg() {
        System.out.println("Hello from RMI Server!");
    }
}

Step 3: Develop Server Program

import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;

public class Server {
    public static void main(String[] args) {
        try {
            ImplExample obj = new ImplExample();
            // Export Object -> Stub
            Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
            // Bind กับ Registry
            Registry registry = LocateRegistry.createRegistry(1099); // Port 1099
            registry.bind("Hello", stub);
            System.out.println("Server ready...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 4: Develop Client Program

import java.rmi.registry.*;

public class Client {
    public static void main(String[] args) {
        try {
            Registry registry = LocateRegistry.getRegistry("localhost", 1099);
            Hello stub = (Hello) registry.lookup("Hello");
            stub.printMsg(); // เรียก Remote Method
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 5-6: Compile & Run

# Compile
javac *.java

# Start RMI Registry (Terminal 1)
rmiregistry 1099

# Run Server (Terminal 2)
java Server

# Run Client (Terminal 3)
java Client
# Output: Hello from RMI Server!

จุดสำคัญ

  • Stub/Skeleton - Proxy จัดการ Network Communication (Java 2+ ไม่ต้อง Skeleton แยก)
  • UnicastRemoteObject.exportObject() - สร้าง Stub สำหรับ Remote Object
  • LocateRegistry.createRegistry(port) - สร้าง Registry Embedded ใน Server (ไม่ต้องรัน rmiregistry แยก)
  • registry.bind("name", stub) - ลงทะเบียนชื่อบริการ
  • Security: ต้องมี SecurityManager หรือ Policy File สำหรับ Remote Code Download (Legacy) Java 2+ ใช้ Serialization Filter แทน

Modern Alternative

ปัจจุบันแนะนำให้ใช้ REST API (Spring Boot, JAX-RS), gRPC, หรือ WebSocket แทน RMI เพราะ Firewall Friendly, Cross-Language, Scalable