提问
这是Java中的示例代码.共享接口:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote {
public Object executeTask(Task t) throws RemoteException;
}
任务(将作为参数传递):
import java.io.Serializable;
public interface Task extends Serializable {
public Object execute();
}
服务器:
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ComputeEngine extends UnicastRemoteObject implements Compute {
public ComputeEngine() throws RemoteException {
super();
}
public Object executeTask(Task t) {
return t.execute();
}
public static void main(String[] args) {
setRmiCodebase();
System.setSecurityManager(new RMISecurityManager());
try {
Compute engine = new ComputeEngine();
Naming.rebind("//localhost:1099/Compute", engine);
System.out.println("ComputeEngine started.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void setRmiCodebase() {
String codebase = System.getProperty("java.rmi.server.codebase");
if (codebase != null)
return;
// set codebase based on location of this clsas (is it in jar or filesistem?)
}
}
客户:
import java.math.BigDecimal;
/**
* Calculates Pi to arbitrary number of digits:
*/
public class Pi implements Task {
public Pi(int digits) {
this.digits = digits;
}
public Object execute() {
return computePi(digits);
}
public static BigDecimal computePi(int digits) {
// compute Pi
}
}
客户主要:
import java.math.BigDecimal;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
public class ComputePi {
public static void main(String[] args) {
setRmiCodebase();
System.setSecurityManager(new RMISecurityManager());
try {
Compute comp = (Compute)Naming.lookup("//localhost:1099/Compute");
Pi task = new Pi(100);
BigDecimal pi = (BigDecimal)comp.executeTask(task);
System.out.println(pi);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void setRmiCodebase() {
String codebase = System.getProperty("java.rmi.server.codebase");
if (codebase != null)
return;
// set codebase based on location of this clsas (is it in jar or filesistem?)
}
}
如您所见,客户端的代码(不仅仅是数据)被传输到服务器并在那里执行,并返回计算结果.服务器不知道类Pi存在,它只知道Task接口.
我需要这样的东西才能在.net环境中工作(如果重要,请使用C#). WCF会很好,但是我正在寻找最简单的解决方案,因此WCF不是强制性的.我什至不知道该使用哪一个关键字来谷歌文档或解决方案.
任何帮助将不胜感激.
最佳答案
.NET本机不支持在另一台计算机上执行的“发送代码”.通常,必要的代码将被编译为程序集,并在客户端调用之前预先安装在服务器上.远程处理和WCF都是如此.您可能会遇到两种远程处理的情况,其中服务器通过WCF调用客户端上的方法,但是我怀疑这不是您想要的.我知道真正在服务器上运行动态代码的唯一方法是生成动态代码,将其作为字符串发送到服务器,然后让服务器将其动态编译为内存中的程序集,然后执行它.如果您有兴趣这样做,请看一下我对类似问题的回答:但是,在大多数情况下,这并不是我所建议的.我建议您首先重新考虑设计,看看是否有任何方法可以以典型的“ .NET方式”完成所需的工作.