Using Javascript with RTW

12. februar 2019

To use RTW with Javascript the best approach is to use the websocket route because it will then return data in json-format. This is a bit different than using the standard RTW-HTTP route in the way that it uses special websocket endpoints. We will describe how to use javascript with websockets to connect to rtw below.

//Here is the way you setup a websocket connect for recieving data from rtw.
//Here you will have to replace yourdomain with the name of your domain, service with the name of your service
//and objectid with the objectid you want to use.
var channel = new WebSocket("ws://websocketdev.rtw.no/yourdomain/service/objectid/channel");
//Here is the way you setup a websocket connect for sending data to rtw. The thing that is different here is that
//behind the last slash it says string instead of channel.
var string = new WebSocket("ws://websocketdev.rtw.no/yourdomain/service/objectid/string");
//Here is the token you can find this in the NDS replace it under.
var token = "tokenHere";
console.log("Connecting....");
waitForConnection();
//The waitForConnction function waits for the connection to be established
//and then sends the token when the connection is up
function waitForConnection(){
if(channel.readyState === 1){
console.log("Connected!");
channel.send('{"token":"'+token+'"}');
console.log("Sendt token")
}
else{
setTimeout(function(){waitForConnection();}, 500);
}
}
//This is the omessage function for the revcieving websocket. Here we get the data from the event
//and echo it out to the javascript console. You may here see your data and work with it if
//you wish to do that.
channel.onmessage = function (event) {
var obj = JSON.parse(event.data);
console.log(obj);
}
//Here is an example for sending data to rtw
//Here it is important to send the token with everytime you send something to rtw. This to identify yourself.
string.send('{"token":"'+token+'", "MESSAGE":"yourmessage");