[英]Rserve: Connection Refused: Connect
我正在嘗試從Java代碼執行R腳本。 這是我有的Java代碼
package pkg;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class Temp {
public static void main(String a[]) {
RConnection connection = null;
try {
/* Create a connection to Rserve instance running on default port
* 6311
*/
connection = new RConnection();
connection.eval("source('D:\\\\r script\\\\TestRserve.R')");
connection.eval("Rserve()");
int num1=10;
int num2=20;
int sum=connection.eval("myAdd("+num1+","+num2+")").asInteger();
System.out.println("The sum is=" + sum);
} catch (RserveException e) {
e.printStackTrace();
} catch (REXPMismatchException e) {
e.printStackTrace();
}
}
}
TestRserve.R如下
library(Rserve)
Rserve()
x= matrix(c(1,2,3,4,5,6))
plot.ts(x)
我使用了來自教程和AFAIK的示例代碼,但Java文件中未執行TestRserve。 我也嘗試過類似下面的方法來執行TestRserve.R
REXP x;
System.out.println("Reading script...");
File file = new File("D:\\r script\\TestRserve.R");
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
System.out.println(line);
x = c.eval(line); // evaluates line in R
System.out.println(x); // prints result
}
}
以下是堆棧跟蹤
線程“主”中的異常org.rosuda.REngine.Rserve.RserveException:無法連接:連接被拒絕:在org.rosuda.REngine.Rserve的org.rosuda.REngine.Rserve.RConnection。(RConnection.java:88)連接。 org.rosuda.REngine.Rserve.RConnection。(RConnection.java:44)處的RConnection。(RConnection.java:60)在functionTest.HelloWorldApp.main(HelloWorldApp.java:17)處
從代碼中可以看出很多關於Rserve的誤解。
首先,Rserve是服務器,Rserve JAR文件提供了與Rserve進行交互的客戶端實現,就像npm
上有JavaScript客戶端一樣。
因此,要通過Rserve調用R腳本,Rserve服務器需要已經啟動並等待接收呼叫。 可以從R使用以下命令完成:
library(Rserve)
Rserve()
或: R CMD Rserve --vanilla
直接從linux bash調用,或者直接使用JavaRuntime API從Java調用它來訪問運行時:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");
盡管這也僅適用於linux。
然后,您應該執行Java客戶端代碼以通過Rserve連接到Rserve服務器並使用所有R命令eval()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.