MQTT error after 5 minutes - react-native

I have a React-native app that I need to connect with IoT (AWS), with websockets. I currently use the package react-native-paho-mqtt to connect my app. Here is my code :
function getClient(onConnect, onConnectionFailed, onConnectionLost,
onMessageArrived) {
logger.trace('getClient()');
const clientID = uuidV4();
// Create a client instance
const client = new Paho.MQTT.Client(signedUrl, clientID); // eslint-disable-line no-undef
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
keepAliveInterval: 15,
onSuccess: onConnect,
onFailure: onConnectionFailed,
});
return client;
}
5 minute after my main connection, I get an error when I try to connect an other client. I get this error: AMQJS0007E Socket error:{0}.. I do not have any more information about the error.
Does anyone know what is happening or how to solve this problem ?

Related

How do I know which network currently connected in MetaMask by WalletConnet react native?

I am developing react native mobile application where user can connect their crypto wallet(MetaMask, Rainbow, etc.) to mobile application. Everything is working well. I have used this (#walletconnect/react-native-dapp) react-native package to achieve this requirement.
After connected the external wallet (MetaMask), later I have to do some transaction by my app.
To do transaction I have to get know which network currently set in MetaMask wallet.
Is there any way to know the current connected network(chainId)to Metamask by this react-native package.
To do the transaction I am using this code.
try {
let dataa = await contract.methods
.transfer(toAddress, value.toString())
.encodeABI();
let txObj = {
// gas: Web3js.utils.toHex(100000),
data: Web3js.utils.toHex(dataa),
from: userWallet,
to: POZ_TOKEN, // Contractor token address
};
try {
const transactionHash = await connector
.sendTransaction(txObj)
.catch((_err: any) => {
Toast.show({
autoHide: true,
text1: t('topUpPoz.transactionFailed'),
type: 'error',
});
});
console.log('transactionHash is =', transactionHash);
Please suggest me anyone.
With #walletconnect/react-native-dapp we can fetch chain ID using connector, sample code is given below.
Note: checkNetworkIdHandler is a custom user defined function to check chainId connected is valid or not.
import {useWalletConnect} from '#walletconnect/react-native-dapp';
//creating a wallet connect connector
const connector = useWalletConnect();
const connectExternalWallet = React.useCallback(() => {
return connector.connect();
}, [connector]);
//below code snippet to be called on wallet connect button click
async function connectWallet(){
try {
let connection = await connectExternalWallet();
let networkStatus = checkNetworkIdHandler(connection.chainId);
}catch (exception) {
console.log("Exception occurred while connecting to metamask");
}
}

Sockit.io can not connect to server by React Native

I use the library socket.io-client": "2.3.0" try to use sockit on React Native.
I try the simple code on server side.
server.js
const
io = require("socket.io"),
server = io.listen(8000);
let
sequenceNumberByClient = new Map();
// event fired every time a new client connects:
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
// initialize this client's sequence number
sequenceNumberByClient.set(socket, 1);
// when socket disconnects, remove it from the list:
socket.on("disconnect", () => {
sequenceNumberByClient.delete(socket);
console.info(`Client gone [id=${socket.id}]`);
});
});
// sends each client its current sequence number
setInterval(() => {
for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
client.emit("seq-num", sequenceNumber);
sequenceNumberByClient.set(client, sequenceNumber + 1);
}
}, 1000);
on client side:
client.js
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:8000");
ioClient.on("seq-num", (msg) => console.info(msg));
node server and then node client
I can see Client connected on server side.
But it is not working on my React Native side even on Android or IOS.
My React Native code like this:
import io from 'socket.io-client';
const ioClient = io.connect("http://localhost:8000");
ioClient.on('connect', () => console.log('connected on React Native'));
ioClient.on("seq-num", (msg) => console.info(msg));
I can't see connected on React Native and nothing happened on my server.
Any help would be appreciated.

Stomp over WebSocket in React Native

Has anyone tried using Stomp protocol over the WebSocket implementation in react native? We are using Stomp for the web application, and it would be great if I did not have build a separate back end for the web and mobile applications.
I haven't found a good way to integrate Stomp with the react native Web Sockets.
I have wrapped the latest typescript / js #stomp/stompjs STOMP client into a React HOC, making use of SockJS library to simulate the websocket. feel free to check it out
var connected =false;
var socket ='';
var stompClient = '';
const send = (param)=> {
let send_message =param;
if (stompClient && stompClient.connected) {
const msg = { name: send_message };
stompClient.send("/app/hello", JSON.stringify(msg), {});
}
}
const connect =()=> {
socket = new SockJS("your endpoint");
stompClient = Stomp.over(socket);
stompClient.connect(
{},
frame => {
connected = true;
stompClient.subscribe("/topic/greetings", tick => {
});
},
error => {
console.log(error);
connected = false;
}
);
}
const disconnect =()=> {
if (stompClient) {
stompClient.disconnect();
}
connected = false;
}
const tickleConnection =()=> {
connected ? disconnect() : connect();
}

Application not connecting to Worklight server

I am using WL.Client.connect(options) to connect to worklight server from my hybrid app and its returing this error (please refer to the attachment).
I have checked the WL console, my app and adapters are deployed without any issues.
Could not find any error messages in the logs.
function performWlConnect() {
return new Promise(function (resolve, reject) {
// Worklight server connection callback configuration
var wlConnectOptions = {
onSuccess: resolve,
onFailure: reject
};
logger.info('Connecting to the worklight server side...');
// Perform connection to the server side
WL.Client.connect(wlConnectOptions);
});
}
Try with a simple connect and print the error you're getting, it might help you better diagnose your flow.
function wlCommonInit() {
WL.Client.connect({onSuccess:onConnectSuccess, onFailure:onConnectFailure});
}
function onConnectSuccess() {
...
}
function onConnectFailure(response) {
WL.Logger.debug(response);
}

Node.js + socket.io + node-amqp and queue binginds when "re" connecting thru socket.io

I have one scenario which is very close to this sample:
One main screen:
this screen (client side) will connect to the socket.io server thru server:9090/scope (io.connect("http://server:9090/scope)) and will send one event "userBindOk" (socket.emit("userBindOk", message)) to the socket.io server;
the server receives the connection and the "userBindOk". At this moment, the server should get the active connection to rabbitmq server and bind the queue to the respective user that just connected to the application thru socket.io. sample:
socket.on("connection", function(client){
//client id is 1234
// bind rabbitmq exchange, queue, and:
queue.subscribe(//receive callback);
})
So far, no problem - I can send/receive messages thru socket.io without problems.
BUT, If I refresh the page, all those steps will be done again. As consequence, the binding to the queue will occur, but this time related to another session of the socket.io client. This means that if I send a message to the queue which is related to the first socket.io session (before the page refresh), that bind should (I think) receive the message and send it to a invalid socket.io client (page refresh = new client.id on the socket.io context). I can prove this behaviour because every time I refresh the page I need to send x times more messages. For instance: I`ve connected for the first time: - so, 1 message - one screen update; refresh the page: I need to send 2 messages to the queue and only the second message will be received from the "actual" socket.io client session - this behaviour will occur as many as I refresh the page (20 page refreshs, 20 messages to be sent to a queue and the server socket.io "last" client will send the message to the client socket.io to render into the screen).
The solutions I believe are:
Find a way to "unbind" the queue when disconnecting from the socket.io server - I didn`t see this option at the node-amqp api yet (waiting for it :D)
find a way to reconnect the socket.io client using the same client.id. This way I can identify the client that is coming and apply some logic to cache the socket.
Any ideas? I tried to be very clear... But, as you know, it`s not so eaey to expose your problem when trying to clarify something that is very specific to some context...
tks
I solved it like this:
I used to declare the rabbitMq queue as durable=true,autoDelete=false,exclusive=false and in my app there was 1 queue/user and 1 exchange(type=direct) with the routing_key name=queueName, my app also used the queue for other client diffent to browsers like android app or iphone app as push fallback, so i use to crear 1 queue for earch user.
The solution to this problem was to change my rabbitMQ queue and exchange declaration. Now i declare the exchange/user as fanout and autoDelete=True, and the user is going to have N queues with durable=true, autoDelete=true, exclusive=true (No. queue = No. clients) and all the queues are bind to the user-exchange(multicast).
NOTE: my app is wirten in django, and i use node+socket+amqp to be able to comunicate with the browser using web.scokets, so i use node-restler to query my app api to get the user-queue info.
thats the rabbitMQ side, for the node+amqp+socket i did this:
server-side:
onConnect: the declaration of the user exchange as fanout, autoDelete, durable. then declaration of the queue as durable, autodelete and exclusive, then the queue.bind to the user-exchange and finaly the queue.subscribe and the socket.disconnect will destroy the queue so there are going to exist queue as client connected the app and this solve the problem of the refresh and allow the user to have more than 1 window-tab with the app:
Server-side:
/*
* unCaught exception handler
*/
process.on('uncaughtException', function (err) {
sys.p('Caught exception: ' + err);
global.connection.end();
});
/*
* Requiere libraries
*/
global.sys = require('sys');
global.amqp = require('amqp');
var rest = require('restler');
var io = require('socket.io').listen(8080);
/*
* Module global variables
*/
global.amqpReady = 0;
/*
* RabbitMQ connection
*/
global.connection = global.amqp.createConnection({
host: host,
login: adminuser,
password: adminpassword,
vhost: vhost
});
global.connection.addListener('ready',
function () {
sys.p("RabbitMQ connection stablished");
global.amqpReady = 1;
}
);
/*
* Web-Socket declaration
*/
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
sys.p(data);
try{
var message = JSON.parse(data);
}catch(error){
socket.emit("message", JSON.stringify({"error": "invalid_params", "code": 400}));
var message = {};
}
var message = JSON.parse(data);
if(message.token != undefined) {
rest.get("http://dev.kinkajougames.com/api/push",
{headers:
{
"x-geochat-auth-token": message.token
}
}).on('complete',
function(data) {
a = data;
}).on('success',
function (data){
sys.p(data);
try{
sys.p("---- creating exchange");
socket.exchange = global.connection.exchange(data.data.bind, {type: 'fanout', durable: true, autoDelete: true});
sys.p("---- declarando queue");
socket.q = global.connection.queue(data.data.queue, {durable: true, autoDelete: true, exclusive: false},
function (){
sys.p("---- bind queue to exchange");
//socket.q.bind(socket.exchange, "*");
socket.q.bind(socket.exchange, "*");
sys.p("---- subscribing queue exchange");
socket.q.subscribe(function (message) {
socket.emit("message", message.data.toString());
});
}
);
}catch(err){
sys.p("Imposible to connection to rabbitMQ-server");
}
}).on('error', function (data){
a = {
data: data,
};
}).on('400', function() {
socket.emit("message", JSON.stringify({"error": "connection_error", "code": 400}));
}).on('401', function() {
socket.emit("message", JSON.stringify({"error": "invalid_token", "code": 401}));
});
}
else {
socket.emit("message", JSON.stringify({"error": "invalid_token", "code": 401}));
}
});
socket.on('disconnect', function () {
socket.q.destroy();
sys.p("closing socket");
});
});
client-side:
The socket intance with options 'force new connection'=true and 'sync disconnect on unload'= false.
The client side use the onbeforeunload and onunload windows object events to send socket.disconnect
The client on socket.connect event send the user token to node.
proces message from socket
var socket;
function webSocket(){
//var socket = new io.Socket();
socket = io.connect("ws.dev.kinkajougames.com", {'force new connection':true, 'sync disconnect on unload': false});
//socket.connect();
onSocketConnect = function(){
alert('Connected');
socket.send(JSON.stringify({
token: Get_Cookie('liveScoopToken')
}));
};
socket.on('connect', onSocketConnect);
socket.on('message', function(data){
message = JSON.parse(data);
if (message.action == "chat") {
if (idList[message.data.sender] != undefined) {
chatboxManager.dispatch(message.data.sender, {
first_name: message.data.sender
}, message.data.message);
}
else {
var username = message.data.sender;
Data.Collections.Chats.add({
id: username,
title: username,
user: username,
desc: "Chat",
first_name: username,
last_name: ""
});
idList[message.data.sender] = message.data.sender;
chatboxManager.addBox(message.data.sender, {
title: username,
user: username,
desc: "Chat",
first_name: username,
last_name: "",
boxClosed: function(id){
alert("closing");
}
});
chatboxManager.dispatch(message.data.sender, {
first_name: message.data.sender
}, message.data.message);
}
}
});
}
webSocket();
window.onbeforeunload = function() {
return "You have made unsaved changes. Would you still like to leave this page?";
}
window.onunload = function (){
socket.disconnect();
}
And that's it, so no more round-robing of the message.