Connecting to Websockets using JavaScript

Jilani
Hi Kailash,
We are trying to connect using JavaScript, but the we are not getting the desired response.
But when I try using Dark Websocket plugin , I am getting the binary response.
Please see the below code:

var ws = new WebSocket("wss://websocket.kite.trade/?api_key=xyz&user_id=abc&public_token=abc");
var message = {"a":"subscribe","v":[408065,884737]};
this.send = function (message, callback) {
this.waitForConnection(function () {
ws.send(message);
if (typeof callback !== 'undefined') {
callback();
}
}, 1000);
};


ws.onmessage = function (evt) {
var messageObj = evt;
console.log(messageObj);

};
  • Kailash
    You should encode your data structure to JSON before you send it. So:

    ws.send(JSON.stringify(message));
  • Jilani
    @Kailash Thanks.
    I have encoded to JSON, now I get the following response
    Blob {size: 1, type: ""}
    But I am not getting the binary content.
    I assume the size is 1 as the Market is closed.
    Let me know if I am missing something.

    Here's the sample code:

    function wssend(){

    var ws = new WebSocket("wss://websocket.kite.trade/?api_key=abc&user_id=xyz&public_token=123");
    ws.binaryType="blob";
    var message = {"a":"subscribe","v":[408065,884737]};
    this.send = function (message, callback) {
    this.waitForConnection(function () {
    ws.send(JSON.stringify(message));
    if (typeof callback !== 'undefined') {
    callback();
    }
    }, 1000);
    };
    ws.onmessage = function (evt)
    {
    var messageObj = evt;
    if(evt.data instanceof Blob)
    {

    evt.data = new Blob();
    console.log(evt.data);
    } else {
    processText(evt.data);
    console.log(messageObj);
    }
    }
    }

    Regards,
    Jilani.
  • Kailash
    When there are no ticks, a 1-byte (null) heart beat is sent. That's what you're seeing. You can try subscribing to MCX instruments.
  • Jilani
    @Kailash is the JavaScript Websocket Library ready?
    I am able to get the response only the size, but not the actual binary data.
    Any help will be highly appreciated!!
  • Kailash
    @Jilani Need a little more time ;( We have client libraries in multiple languages in the pipeline. Could you give the Python WebSocket library a shot for the time being?
  • Jilani
    @Kailash any update on the JavaScript or Android Libraries?
Sign In or Register to comment.