本文中描述的內容在本文發表前未獲得運行成功,其中原因複雜,比如本人下載的是JavaFX for Eclipse 3.2.2的plugin,但實際使用的是更高版本。但很多其他用戶也同時遇到了這樣的問題。據廣大使用人羣解釋,可暫定爲“JavaFX Complier”的BUG。但因JavaFX Script尚未正式release,所以我們相信在不久的將來這段代碼就能夠獲得成功運行。
迴歸正文。JavaFX作爲RIA的解決方案之一,最重要的功能之一就是要具備和服務器端的異步通信能力。如何獲取與服務器端的通信能力呢?JavaFX有多種解決方案。我們今天在這裏介紹的是其中的一種,使用RMI(遠程方法調用)。
JavaFX Script與Java是進行了全面整合了的(不過現在compiler還有bug,要不然這個程序就能運行成功),所以使用JavaFX和Java的聯合能夠很方便地與服務器交互。
關於RMI的種種概念,在此就不多說了。先看服務器端的代碼:
ServerInterface接口(Java代碼):
package server;
import java.rmi.Remote; import java.rmi.RemoteException;
public interface ServerInterface extends Remote {
public String ping(String fileName) throws RemoteException;
}
ServerImpl類(Java代碼):
package server;
import java.io.*; import java.rmi.*; import java.rmi.server.UnicastRemoteObject;
public class ServerImpl extends UnicastRemoteObject implements ServerInterface {
private String name;
public ServerImpl() throws RemoteException{ super(); }
public String ping(String s){ return "Hello " + s; }
}
ServerMain類(Java代碼):
package server;
import java.rmi.*; import java.rmi.registry.LocateRegistry;
public class ServerMain {
public static void main(String argv[]) {
try {
LocateRegistry.createRegistry(1099);
ServerInterface s = new ServerImpl(); Naming.rebind("//127.0.0.1/Server", s);
} catch(Exception e) { System.out.println("Server: "+e.getMessage()); e.printStackTrace(); } } }
客戶端代碼如下:
ConnectionHelper類(Java代碼):
package client;
import java.rmi.*; import server.ServerInterface;
public class ConnectionHelper {
public static ServerInterface getConnection() throws Exception { return (ServerInterface) Naming.lookup("rmi://127.0.0.1:1099/Server"); }
}
MyClient.fx代碼(JavaFX Script):
import java.lang.*; import javafx.ui.*; import java.rmi.*;
//接下來這兩個import語句可能提示找不到Symbol,這就是我前面說的JavaFX Complier可能的bug。
import server.ServerInterface; import client.ConnectionHelper;
class ButtonClickModel { attribute numClicks: Number; }
var model = new ButtonClickModel();
var win = Frame { width: 200 content: GridPanel { border: EmptyBorder { top: 30 left: 30 bottom: 30 right: 30 } rows: 3 columns: 1 vgap: 10 cells: [ Button { text: "Click to make RMI connection!" mnemonic: I action: operation() {
try {
var remoteServer:ServerInterface = ConnectionHelper.getConnection();
var results = remoteServer.ping("Test"); System.out.println("response: {results}"); model.numClicks++;
} catch (e:Exception) { System.out.println("exception: {e}"); } } },
Label { text: bind "Number of RMI connections: {model.numClicks}"
} ] } visible: true };