Sockit.io can not connect to server by React Native - 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.

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");
}
}

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?

How to use setState with ssdp m-search discovery?

I am using SSDP search message to discover devices with connected same network but when i tried to call setState hooks inside client.on function I only get one device informations.
I initialized my state value in this way
const [deviceList, setDeviceList] = useState([]);
And create a function for the client to add deviceList as it is found
const getAllDevices = () => {
var Client = require('react-native-ssdp-remote').Client,
client = new Client();
client.search('urn:dial-multiscreen-org:service:dial:1');
client.on('response', function (headers) {
const url = new URL(headers.LOCATION);
if (url != null) {
if (!deviceList.includes(url)) {
setDeviceList([...deviceList, url]);
}
}
});
};
and called this function inside useEffect
useEffect(() => {
getAllDevices();
}, []);
There are 4 devices connected to same network and it goes into setDeviceList process 4 times but i can only get one device. Could you please support.
Thanks.
I think this is more of a race condition instead of a library issue.
Give it a try with using functional update on setDeviceList.
setDeviceList(deviceList => {
return [...deviceList, url]
}

Socket.io expo react native clients repeatedly changing socket.id and shows disconnect=true

I am new to socket.io and was using guide https://snack.expo.io/#alexandrius/socket.io-client
On my server side (node.js) i see that socket.id keeps changing repeatedly
And on by expo client side in console.log i see :
Here is my code for client side:
componentDidMount() {
//console.log(socket);
//socketIO();
this.socket = io(URL, { transports: ["websocket"] });
this.socket.on("connect", () => {
this.setState({ isConnected: true });
});
this.socket.on("ping", (data) => {
console.log(data);
});
GetLocation();
}
When i connect to web page from phone it fires up socket and on server side does not change id repeatedly.
No sure is there any bug with expo react native socke.io library or i am doing something wrong
I fixed it my upgrading my expo to the version 36

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();
}