Vini
Vini

Reputation: 2134

Rserve: Connection Refused: Connect

I am trying to execute a R script from my Java code. This is the java code I have

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();
    }
}
}

The TestRserve.R is as follows

  library(Rserve)
  Rserve()
  x= matrix(c(1,2,3,4,5,6))
  plot.ts(x)

I have used a sample code from a tutorial and AFAIK, the TestRserve is not being executed in the Java file. I have also tried something like below to execute the 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
            }
        }

The following is the stack trace

Exception in thread "main" org.rosuda.REngine.Rserve.RserveException: Cannot connect: Connection refused: connect at org.rosuda.REngine.Rserve.RConnection.(RConnection.java:88) at org.rosuda.REngine.Rserve.RConnection.(RConnection.java:60) at org.rosuda.REngine.Rserve.RConnection.(RConnection.java:44) at functionTest.HelloWorldApp.main(HelloWorldApp.java:17)

Upvotes: 0

Views: 4363

Answers (1)

brijs
brijs

Reputation: 545

There are a bunch of misconceptions about Rserve that are discernible from your code.

First of all, Rserve is a server and the Rserve JAR files provide the client implementations to interact with Rserve, just like there are JavaScript clients on npm.

Thus to call R scripts through Rserve, Rserve server needs to be already started and waiting to receive calls. This can be done from R using:

library(Rserve)
Rserve()

or,: R CMD Rserve --vanilla directly from linux bash or,calling it directly from Java using JavaRuntime API to access the runtime:

Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");

although this also works for linux only.

Then you should execute your Java client code to connect to the Rserve server and eval() all your R commands through Rserve.

Upvotes: 1

Related Questions