Search code examples
javascriptrwebsocketrserve

Connecting to Rserve with WebSockets using javascript


I have Rserve installed on my Ubuntu server. I would like to interact with it using javascript. I know that rserve npm "provides a javascript implementation of the websocket Rserve protocol" but it do not seems to be maintain anymore and I would like to be able to do it with native javascript (or JS libraries like jQuery). I am trying to connect and have a dedicated R session that could be used as a console.

This is my Rserv.conf (From this documentation)

remote enable
websockets.qap enable
websockets.port 8080

This is my JS

var ws = new WebSocket("ws://my.app:8080");
ws.onopen = function()
{
    ws.binaryType = 'arraybuffer'
    ws.send("Hello world");
    console.log("Message is sent...");
 };

 ws.onmessage = function (evt) 
 { 
      console.log("Message received:"); 
      var received_msg = evt.data;
      console.log(received_msg);
  };

 ws.onclose = function()
 { 
      console.log("Connection is closed..."); 
 };

I receives two messages: 

Message is received:
Rsrv0103QAP1

--------------

Message is received:
ArrayBuffer {}

After that, the connection closes. How do I keep the connection open? How can I convert the ArrayBuffer so I can get the content of the response?


Solution

  • Have a look at rserve-js - it is a full Rserve client for JavaScript and it supports both OCAP and plain QAP mode (including OOB callbacks). We use it in RCloud very extensively which is also possibly a good source to look for its use (in OCAP mode which is more secure and suitable for web applications) - it particular since it actually does what you're trying to do (and much more).