這是一個有關RMI的問題。我有4個.class文件接口,它是實現,一個名爲server的類和一個名爲client的類。該課程的內容如何打印,我還沒有開始CMD
開始rmiregistry中i之後開始這就好比服務器:
import java.rmi.Naming;
public class Server {
public static void main(String args[]) {
try {
to_Server_Impl toServer = new to_Server_Impl();
Naming.rebind("Server", toServer);
} catch(Exception exc) {
System.out.println(exc);
}
}
}
然後我啓動其代碼是客戶端:
import java.rmi.Naming;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
to_Server_Intf s_Intf = (to_Server_Intf)Naming.lookup("rmi://127.0.0.1/Server");
do {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String message_to_send = null;
System.out.println("===Enter your message===");
message_to_send = br.readLine();
// sending a message to the server
String reply = s_Intf.send(message_to_send);
System.out.println(reply);
}while(true);
}catch(Exception exc) {
System.out.println(exc);
}
}
}
使用遙控對象的引用i調用函數send
,其代碼如下:
import java.rmi.*;
import java.rmi.server.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class to_Server_Impl extends UnicastRemoteObject implements to_Server_Intf{
public to_Server_Impl() throws Exception{ }
@Override
public String send(String str){ // this function receives the message from the Client.
// this method indirectly replies,by calling reply and then returning the replies string
String receivedString = str;
System.out.println(receivedString);
System.out.println();
String reply = reply();
return reply;
}
@Override
public String reply() { // this function replies the Client
String replyString = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
replyString = br.readLine();
}catch(Exception exc) {
System.out.println(exc);
}
return replyString;
}
}
當我調用上述類的print
語句的方法時,在「server
」窗口中打印消息。這怎麼可能?
客戶端窗口:(客戶端發送的消息)
服務器窗口:(消息獲取打印服務器窗口上(呼叫被定向到類to_Server_Impl
)的功能。怎麼樣?)
我稱之爲類'to_Server_Impl'的send方法。它如何出現在「服務器」控制檯上? – 2011-12-22 11:25:55
因爲to_Server_Impl是遠程對象的接口的實現。在客戶端中,您使用Naming.lookup查找遠程對象,然後調用該方法。然後這個方法實際上由to_Server_Impl在服務器上執行。所以該消息被打印在服務器上。 – Tudor 2011-12-22 11:28:58
您是否需要關於RMI如何工作的解釋? – Tudor 2011-12-22 11:41:49