1

I have tried to connect socket with React Native mobile App. Node server socket.io is working i have use with react web, But when i use React Native Mobile App there was not working

Client (React Native

import io from 'socket.io-client';

const ENDPOINT = "http://192.168.1.3:7000";
const socket = io(ENDPOINT, {transports: ['websocket']});

const getMessage = () => {
  socket.on('getMessage', (data) => {
    console.log('socket data', data);
  })
};

const sendMessage = () => {
  var userid = log.userid
  var message = "msg from app"
  socket.emit('send msg', { userid, message });
}

Server (Node Js)

const app = express();
const server = app.listen(7000);
const io = require('socket.io')(server, {
cors : {
    origin:'*'
  }
});

io.on("connection",(socket)=>{
  socket.on('sendMessage',({userid, message})=>{
    io.emit('getMessage',{userid, message});
  })
})

3 Answers 3

3

dev! I solved this just not using socket.io. I got that Socket.io is not a good choice in mobile apps. Use WebSocket API instead.

REACT COMPONENT

import React from 'react';
import { View, Text } from 'react-native';

class WebSocketConnection extends React.Component {

    constructor(props) {
        super(props);
        this.webSocket = this.webSocket.bind(this);
    }

    webSocket() {
        const ws = new WebSocket('ws:172.16.20.201:8080');

        ws.onopen = (e) => {
            console.log('connected on wsServer');
        }
        
        ws.addEventListener('open', function (event) {
            ws.send('Hello from React Native!');
        });
        
        ws.addEventListener('message', function (event) {
            this.message = event.data;
            console.log('Message from server ', event.data);
        });
        
        ws.onerror = (e) => {
            console.log(e);
        }
    }
    
    render() {
        return (
            <View>
                <Text>
                    Socket.io YES
                </Text>
            </View>
        )
    }

    componentDidMount() {
        this.webSocket();
    }

}

export default WebSocketConnection;

SERVER

/**
 * Create WebSocket server.
 */

const WebSocket = require('ws');
const serverWs = new WebSocket.Server({
  port: 8080
});

let sockets = [];
serverWs.on('connection', function(socket) {
  sockets.push(socket);

  console.log(`connectet client`);

  // When you receive a message, send that message to every socket.
  socket.on('message', function(msg) {
    console.log(msg);
    sockets.forEach(s => s.send(msg));
  });

  // When a socket closes, or disconnects, remove it from the array.
  socket.on('close', function() {
    sockets = sockets.filter(s => s !== socket);
  });
});

While using Express, I bind this server inside /bin/www and work fine to me.

Sign up to request clarification or add additional context in comments.

2 Comments

hi. I am having trouble also using socket.io then I found your answer . Can you please share with me a bit more information like what to install on the server or on react something like that . really appreciate it . thank you
Hi, dev. In server you will have a native WebSocket server. MasteringJs . In client side you will have a native WebSocket client (even ReactNative). Mozilla .I'm not sure I've helped you, but if not, tell me more, please! Blessings!
1

I was able to work when i changed the react-native to use the ws protocol. My code was as below

useEffect(()=>{
        const socket = io("ws://localhost:3000");
        socket.on("connect", () => {
            console.log(socket.connected); // true
        });
    },[])

Comments

0

Your code should work.

Just you want to change the topic in emit to "sendMessage"

    const sendMessage = () => {
        var userid = log.userid
        var message = "msg from app"
        socket.emit('sendMessage', { userid, message });
    }

Add error login just after creating the socket like bellow

    io.on("connect_error", (err) => {
     console.log(`connect_error due to ${err.message}`);
    });

It may help to find the error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.