Hi,
I have integrate websocket with React Native. I got websocket response properly with node JS but when I try it with React Native, websocket connection is established but it return empty object i.e, {“isTrusted”:false,“data”:{}} not even binary encoded message.
Please provide solution or reason why I am getting empty object not the encoded message. Also provide how to decode the message after receiving non-empty object in React Native.
Thank you
My implementation code:
import React, {useEffect} from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {Buffer} from 'buffer';
const Upstox = () => {
useEffect(() => {
connectWebSocket();
}, []);
const getUrl = () => {
return new Promise(async (resolve, reject) => {
const apiUrl = 'https://api-v2.upstox.com/feed/market-data-feed/authorize';
const auth_token = 'AUTH_TOKEN';
let headers = {
'Content-type': 'application/json',
Authorization: 'Bearer ' + auth_token,
};
try {
// Make the API request
const response = await fetch(apiUrl, {
method: 'GET',
headers: headers,
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const res = await response.json();
const url = res.data.authorizedRedirectUri;
resolve(url);
} catch (error) {
console.error('Error:', error);
reject(error);
}
});
};
const connectWebSocket = async () => {
const wsUrl = await getUrl();
return new Promise((resolve, reject) => {
const ws = new WebSocket(wsUrl);
ws.addEventListener('open', () => {
console.log('connected');
resolve(ws);
setTimeout(() => {
const data = {
guid: 'someguid',
method: 'sub',
data: {
mode: 'full',
instrumentKeys: ['NSE_EQ|INE155A01022'],
},
};
ws.send(Buffer.from(JSON.stringify(data)));
}, 1000);
});
ws.addEventListener('close', () => {
console.log('disconnected');
});
ws.addEventListener('message', data => {
// let res = JSON.stringify(decodeProfobuf(data));
let res = JSON.stringify(data);
console.log(res); // gives {"isTrusted":false, "data":{}} empty object
});
ws.addEventListener('error', error => {
console.log('error:', error);
reject(error);
});
});
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => connectWebSocket()}>
<Text style={{fontSize: 22, fontWeight: 'bold', color: 'black'}}>
Upstox WebSocket
</Text>
</TouchableOpacity>
</View>
);
};