Using Rserve how to make TCP/IP connection to run r code located on remote machine
install.packages('Rserve')
directory structure will be soething like C:\Users\username\Documents\R\win-library\3.4\Rserve\java it will contain two jar
- Rengine.jar
- Rserver.jar
it will take four parameters host machine name,port no default 6312,username,password to connect to the machine in which you want to run R code
public static RConnection connection = null;
public static RConnection open(RConnection connection,String hostname,int port,String username,String password) throws RserveException{
connection = new RConnection(hostname,port);
connection.login(username,password);
return connection;
}
public static RConnection open(RConnection connection) throws RserveException{
connection = new RConnection();
return connection;
}
to run code on windows it will take four \\ in the path
public static String scriptPAth="put the path which you want to pass";//in the src variable
public static void scriptloading(RConnection connection,String filename) throws RserveException{
String path= "source('C:\\\\Users\\\\guptakas\\\\Rscripts\\\\"+filename+"')";
connection.eval(path);
}
here is a function to add
public static REXP funcall(RConnection connection,String funcname,int num1,int num2) throws RserveException, REXPMismatchException{
return connection.eval(funcname+"("+num1+","+num2+")");
}
public static void close(RConnection connection) throws RserveException{
if(connection !=null){
connection.close();
}
}
- Rserve.exe should be running
- to run Rserve.exe library('Rserve') Rserve()
- it will acts as a listner
- connect
connection = open(connection,"Ip addres",6311,"username", "password");
- load the scripts it will take scriptname
scriptloading(connection,"add.R");
- contents of add.R similary defines your own mwthod
myAdd=function(x,y){
sum=x+y
return(sum)
}
- custom method to run code
int sum=funcall(connection,"myAdd",10,20).asInteger();
- print or return it or consume the way you want
System.out.println("The sum is=" + sum);
public static void test1() throws RserveException {
System.out.println("entering");
try {
/* Create a connection to Rserve instance running
* on default port 6311
*/
//connection = new RConnection("127.0.0.1",6311);
//connection.login("guptakas", "Microfocus@123");
connection = open(connection,"Ip addres",6311,"username", "password");
System.out.println("connection established");
/* Note four slashes (\\\\) in the path */
scriptloading(connection,"add.R");
int sum=funcall(connection,"myAdd",10,20).asInteger();
System.out.println("The sum is=" + sum);
} catch (RserveException e) {
e.printStackTrace();
} catch (REXPMismatchException e) {
e.printStackTrace();
}finally{
close(connection);
if(connection.isConnected())
{
System.out.println("still connected");
}
System.out.println("connection close");
}
}
RJavaIntegration rconnect = new RJavaIntegration();
rconnect.test1();