title: Rserve: Connection Refused: Connect
body: <p>I am trying to execute a R script from my Java code.
  This is the java code I have</p>
  
  <pre><code>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();
      }
  }
  }
  </code></pre>
  
  <p>The TestRserve.R is as follows</p>
  
  <pre><code>  library(Rserve)
    Rserve()
    x= matrix(c(1,2,3,4,5,6))
    plot.ts(x)
  </code></pre>
  
  <p>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</p>
  
  <pre><code>        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
              }
          }
  </code></pre>
  
  <p>The following is the stack trace</p>
  
  <blockquote>
    <p>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)</p>
  </blockquote>