Stomp over WebSocket in React Native - 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();
}

Related

Is there a way to multi browser communicate each other without peers?still able to communicate after lose peers connecting?

Is there a way to multi browser communicate each other without peers?or still able to communicate after lose peers connecting?
I created sample with gun.js like below:
server.js:
const express = require('express')
const Gun = require('gun')
const app = express()
const port = 8000
app.use(Gun.serve)
const server = app.listen(port, () => {
console.log("Listening at: http://localhost://" + port)
})
Gun({web: server})
test.ts on angular demo:
gun = GUN({
peers: ['http:localhost:8000/gun']
});
data: any;
initDate(): void {
this.gun.get('mark').put({
name: "Mark",
email: "mark#gun.eco",
});
}
listenDate(): void {
this.gun.get('mark').on((data, key) => {
console.log("realtime updates:", data);
this.data = data;
});
}
submit(): void {
this.gun.get('mark').get('live').put(Math.random());
}
I start server.js as a peer and start angular app,open two broswer with same url,the two broswer communicate well.
but after i stop server.js , the two broswer are unable to communicate each other.
Is there a way to the two browser communicate each other without server.js?or how still able to communicate after I stop server.js?

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.

StompJs only works in debugging mode - React Native

import * as Stomp from "stompjs";
import _ from "lodash";
export const MESSAGE_TYPE_CHAT_TYPING = "ChatTyping";
export const MESSAGE_TYPE_CHAT_MESSAGE = "ChatMessage";
export const RECONNECT_DELAY = 3000;
export function wsConnect(user, callback, ondisconnected) {
const webSocket = Stomp.client(url);
webSocket.debug = () => {};
webSocket.connect({},() => {
callback ? callback(webSocket) : _.noop();
},
error => {
// console.log(error);
console.log("Connection lost...");
if (ondisconnected) {
ondisconnected();
}
}
);
return webSocket;
}
The connection between the StompJs over WebSocket is established only when the app is in debugging mode.
I recently came across the same problem and fixed it by installing text-encoding package and enabling forceBinaryWSFrames and appendMissingNULLonIncoming properties
npm install text-encoding --save
Add import * as encoding from 'text-encoding'; to App.js
const client = Stomp.over(socket);
client. Connect({
forceBinaryWSFrames:true,
appendMissingNULLonIncoming:true
}, (frame) => {
console.log('Connected: ' + frame);
});

Chrome on Android not connecting to peer over WebRTC

I'm building a WebRTC app with a central electron app that browsers connect to. The scenario I'm testing is running the electron app on my computer (Ubuntu 16.04) and connecting from chrome (69) on Android (7.0). Following the debugging the offer, answer and candidate are passed, but fails on the last stop of generating the connection. The ice connection state switchs to "checking" then "failed". I'm able to load the browser app on my laptop and connect to an electron app on the same computer.
Should I be using a collection of ice servers? What do I need to make the WebRTC connection more robust? Should I not write my own signaling process and use something pre-made? Is their anyway to debug the reason why the connection failed? For debugging I've tried the webrtc debugging tab on chrome but all it says is connection failled at the bottom of the stack.
The configuration for my RTCPeerConnection is:
const configuration = {
"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }]
};
This is the code I use to form iniate the connection to the electron app from the browser app (The function are attached to a ts class which are called in order: setupPeerConnection, setupDataChannel, makeOffer):
setupPeerConnection(gameID:string) {
this.gameID = gameID;
let configuration:RTCConfiguration = {
"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }]
};
this.connection = new RTCPeerConnection(configuration);
const that:PeerConnection = this;
//Definition of the data channel
this.connection.ondatachannel = function(ev:RTCDataChannelEvent) {
};
//When we get our own ICE Candidate, we provide it to the other Peer.
this.connection.onicecandidate = function(event:RTCPeerConnectionIceEvent) {
if (event.candidate && that.connectedToGame) {
that.serverConnection.send({
type: "candidate",
candidate: event.candidate
});
}
};
this.connection.oniceconnectionstatechange = function(e:Event) {
let iceState:RTCIceConnectionState = this.iceConnectionState;
console.log("Changing connection state:", iceState)
if (iceState == "connected") {
console.log("Connection established with server");
} else if (iceState =="disconnected" || iceState == "closed") {
// We lost the user
that.connectedToGame = false;
that.onLeave();
}
};
}
setupDataChannel(onopen:(error:ErrorEvent)=>void, onmessage:(message:MessageEvent)=>void) {
let dataChannelOptions:RTCDataChannelInit = <RTCDataChannelInit>{
reliable: true
};
this.dataChannel = this.connection.createDataChannel(this.gameID + "-dataChannel", dataChannelOptions);
this.dataChannel.onerror = function (error:ErrorEvent) {
console.log("Error on data channel:", error);
};
this.dataChannel.onmessage = onmessage.bind(this);
this.dataChannel.onopen = onopen;
this.dataChannel.onclose = function() {
console.log("Channel closed.");
};
}
makeOffer() {
let that:PeerConnection = this;
this.connection.createOffer().then(function (offer:RTCSessionDescriptionInit) {
that.serverConnection.send({
gameID: that.gameID,
type: "offer",
offer: offer
});
that.connection.setLocalDescription(offer);
}, function (error) {
console.log("Error contacting remote peer: ", error);
});
}

How to check internet connection every http request in react native and display alert message?

I'm just trying to check internet connection when app launches and also check internet connectivity before calling HTTP Request.I have seen some example but it's confusing for me.Please guide me.
You can use the NetInfo API from react native.
Here is the example:
componentDidMount() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
}
_handleConnectivityChange = (isConnected) => {
this.setState({
isConnected,
});
};
render() {
return (
<View style={styles.container}>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
);
}
}
Thereby the above code lets you know if you are having internet before making any api call in your app.
You can refer https://facebook.github.io/react-native/docs/netinfo.html for more.
Here is the example:
import { NetInfo,Alert } from 'react-native';
const netStatus = await NetInfo.fetch()
if (netStatus === 'none' || netStatus === 'NONE') {
Alert.alert("Internet not connected ")
return []
}
There probably is a better way to do this, but you could do a console.log() before the HTTP request and pass in parameters of the API, if you get a result of the title in your console, then you're connected to the internet, otherwise you're not.
You should hook this into your api calls before making them. In such case a higher order function would be useful.
import NetInfo from "#react-native-community/netinfo";
import api from "./MyApi"
//higher order function for api calls
const connectionWrapper = async (errorHandler, apiRequest) => () => {
NetInfo.fetch().then(state => {
return state.isConnected
? errorHandler(state)
: apiRequest()
})
}
//use connection wrapper to build your resource calls
const apiCall = connectionWrapper(
state => ...handleError,
api.resource({ myParams : "myParams"})
)
//now you can reuse api call which should return a promise or anything else that you want
var firstCall = apiCall()
var secondCall = apiCall()
var thirdCall = apiCall()