Karthik
Karthik

Reputation: 35

Using Socket.io not working in React Native Mobile App

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

Upvotes: 1

Views: 6364

Answers (3)

mgms_kumara
mgms_kumara

Reputation: 41

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

Upvotes: 0

Arjun Nair
Arjun Nair

Reputation: 111

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
        });
    },[])

Upvotes: 1

moigamijunior
moigamijunior

Reputation: 135

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.

Upvotes: 3

Related Questions