How to Send Data from Device that hotspot On to other device that connected with hotspot in react-native
Asked Answered
A

2

2

I am developing a message in which devices can communicate over hotspot wifi. I have 2 Devices A and B. Device A makes a hotspot and runs the server then Device B joins Hotspot and sends message to Device A that it is Prferctly Working. But Device A cannot able to send messages to Device B I found out that the gateway Ip of Device A is 0.0.0.0 (its destination or It's directly connected because It creates a Hotspot and server). I implement this Answer How To Send & Receive Data Over Wifi Without Internet In React-Native

Having a Problem in sending messages to Device A(this creates Hotspot) from Device B(this device Join Hotspot)

import React, {useState} from 'react';
import {View, Text, Button, StyleSheet, FlatList} from 'react-native';
import { NetworkInfo } from 'react-native-network-info';
var net = require('net');


const createServer = (chats, setChats) => {
    const server = net.createServer((socket) => {
        console.log('server connected on ' + socket.address().address);
    
        socket.on('data', (data) => {
          let response = JSON.parse(data);
            setChats([...chats, {id:chats.length+1, msg:response.msg}]);
        //   console.log('Server Received: ' + data);
        //   socket.write('Echo server\r\n');
        });
    
        socket.on('error', (error) => {
          console.log('error ' + error);
        });
    
        socket.on('close', (error) => {
          console.log('server client closed ' + (error ? error : ''));
        });
      }).listen(6666, () => {
        console.log('opened server on ' + JSON.stringify(server.address()));
      });
    
      server.on('error', (error) => {
        console.log('error ' + error);
      });
    
      server.on('close', () => {
        console.log('server close');
      });
    
    return server;
};


const ServerScreen = ({navigation}) => {
    const [server, setServer] = useState(null);
    const [chats, setChats] = useState([]);
    const [ip, setIp] = useState('');
   
    
    return <View>
        {ip.length > 0? <Text>Server IP: {ip}</Text>: <Text>Server Screen</Text>}
        <Button title="Start Server" onPress={async () => {
            if(!server)
              setServer(createServer(chats, setChats));
            try{
              let temp_ip = await NetworkInfo.getIPV4Address();
              setIp(temp_ip);
            }catch(e){
              console.log(e.message);
            }
        }}/>
        <Button title="Stop Server" onPress={() => {
            if(server){
                server.close();
                setServer(null);
            }
        }}/>
        <Button title="Go to Client Screen" onPress={() => navigation.navigate('Client')}/>
        {server ? <Text>Server is on</Text>: null}
        <FlatList
            data={chats}
            renderItem={({item}) =>{
                return <Text style={{margin:10, fontSize:20}}>{item.msg}</Text>;
            }}
            keyExtractor={item => item.id}
        />
    </View>;
};

const styles = StyleSheet.create({});

export default ServerScreen;

ClientScreen

import React, {useState, useEffect} from 'react';
import {View, Text, Button, FlatList, TextInput} from 'react-native';
import { NetworkInfo } from 'react-native-network-info';
var net = require('net');
const createClient = (ip, chats, setChats) => {
    const client = net.createConnection(6666,ip, () => {
        console.log('opened client on ' + JSON.stringify(client.address()));
        
      });
  
      client.on('data', (data) => {
        setChats([...chats, {id:chats.length+1, msg:data}]);
      });
  
      client.on('error', (error) => {
        console.log('client error ' + error);
      });
  
      client.on('close', () => {
        console.log('client close');
      });
      return client;
};

    const ClientScreen = ({navigation}) => {
    
        const [client, setClient] = useState(null);
        const [chats, setChats] = useState([]);
    
        /* //On Single Application:
        useEffect(async () => {
            let ip = await NetworkInfo.getIPV4Address(); //await NetworkInfo.getGatewayIPAddress();
            setClient(createClient(ip));
    
            return () => {};
        }, []); */
    
    
    
        //On different Applications:
        useEffect(async () => {
            let ip = await NetworkInfo.getGatewayIPAddress();
            setClient(createClient(ip));
    
            return () => {};
        }, []);
    
        return <View>
            <Text>Client Screen</Text>
            <Button title="Stop Client" onPress={() => {
                if(client){
                    client.destroy();
                    setClient(null);
                }
            }}/>
            {client ? <Text>Client is on</Text>: null}
            <FlatList
                data={chats}
                renderItem={({item}) =>{
                    return <Text style={{margin:10, fontSize:20}}>{item.msg}</Text>;
                }}
                keyExtractor={item => item.id}
            />
            <TextInput placeholder="Type a message" placeholderTextColor="black" style={{margin:10, borderWidth:2, color:'black'}} onSubmitEditing={({nativeEvent: {text}}) => {
                if(client){
                    client.write(JSON.stringify({msg:text, id:1}));
                }
            }}/>
        </View>;
    };
    
    export default ClientScreen;
Afterburning answered 29/7, 2022 at 6:18 Comment(0)
A
0

Thanks for the question. You don't need to have the gatewayIP for Device A as once Device B connects, we will have a "connection" event triggered on Device A, from which, we can get the socket connection object.

You can send messages (from Main Device) to other devices (Client Devices) by:

  1. Saving the socket connection object that you get when the client is connected with the server.
  2. Use the socket object then to send messages to the connected client.

You can save the client socket object by listening to the "connection" event, like this,

io.on("connection", (socket) => {
  // ...
});

Once, you have the socket object, use the socket.send(msg) method to send your desired msg to the client.

Augustina answered 29/7, 2022 at 12:24 Comment(1)
Can you please add this connection info function in my code Already provide complete codeAfterburning
F
0

var net = require('react-native-tcp');
Feline answered 7/10, 2022 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.