【问题标题】:Rserve: Connection Refused: ConnectRserve:连接被拒绝:连接
【发布时间】:2016-08-16 08:48:01
【问题描述】:

我正在尝试从我的 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 中的示例代码,TestRserve 没有在 Java 文件中执行。我也尝试过类似下面的方法来执行 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.RConnection.(RConnection.java:88) 在 org.rosuda.REngine.Rserve.RConnection.(RConnection.java:60) 在 org.rosuda.REngine.Rserve.RConnection.(RConnection.java:44) 在函数Test.HelloWorldApp.main(HelloWorldApp.java:17)

【问题讨论】:

    标签: java r exception rserve


    【解决方案1】:

    从您的代码中可以看出许多关于 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服务器和eval()你所有的R命令通过Rserve。

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2018-08-26
      • 2017-08-10
      • 2015-01-30
      • 1970-01-01
      相关资源
      最近更新 更多