Terdtai Watanatien
Terdtai Watanatien

Reputation: 41

Socket IO with ReactNative

I try to use SocketIO in ReactNative by follow this link https://github.com/facebook/react-native/issues/4393,
On IOS it work very well but Android it could not work Result Of Socket Object connected:false

index.android.js

window.navigator.userAgent = 'react-native';//'react-native';

const io = require('socket.io-client/socket.io');

export default class testApp extends Component {
    componentWillMount(){
        this.socket = io.connect('http://localhost:3000', {
            jsonp: false,
            transports: ['websocket'] 
        });
        // Socket Object connected:false
    }
    componentDidMount(){
        console.log(this.socket);
        this.socket.on('connect', () => {
            console.log('ready to emit')
            console.log('connected!');
        });
    }
    // Other Code
}

package.json:

"react-native": "0.35.0",
"socket.io-client": "^1.5.1"

I could not find a similar problem. Am I missing something?

edited : I'm not sure can I test socketIO in localhost with ReactNative but It's work when I test on IOS emulator

edited2 : My fault It cannot test on local environment server but It's work on IOS not android Can Anybody Explained Why?

Upvotes: 4

Views: 8939

Answers (4)

M Mahmud Hasan
M Mahmud Hasan

Reputation: 1173

may be this will through error

import io from "socket.io-client/socket.io"

Then just add below line....

import io from "socket.io-client/dist/socket.io";

then in componentDidMount or useEffect function just add below line. Never use it under constructor of class component.

 var socket = io("https://localhost.com:3000", { jsonp: false });
        // client-side
        socket.on("chat_message", (msg) => {
            console.log(msg);
        });

Upvotes: 0

user11313461
user11313461

Reputation:

const Local = Platform.OS === 'ios' ? 'http://localhost:3000' : 'http://10.0.2.2:3000'
        import io from "socket.io-client";

    //
           this.socket = io(Local);
           //  console.log(this.socket)
            this.socket.emit(Socket_category, Socket_online_subset);
            this.socket.on(Socket_connection_name, this.onReceivedMessage);

onReceivedMessage =(messages)=> {consol,log(message)}

io.on('connection', function (client) {console.log('User Joined :)')

    client.on(Path_Socket.Socket_category, function (room_name) {
      console.log('joined room online ;) '+room_name);

      client.join(room_name);
  })

}

  io.sockets.in(Socket_online_subset)
            .emit(Socket_connection_name, data(any thing));

Upvotes: 1

user11313461
user11313461

Reputation:

this FullExample for Socket.io in clint ( I Hope Work for you )

import React from 'react';


import SocketIOClient from 'socket.io-client'
const USER_ID = '@userId';

export default class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      userId: null
    };

    this.determineUser = this.determineUser.bind(this);
    this.onReceivedMessage = this.onReceivedMessage.bind(this);
    this.onSend = this.onSend.bind(this);
    this._storeMessages = this._storeMessages.bind(this);

    this.socket = SocketIOClient('http://localhost:3000');
    this.socket.on('message', this.onReceivedMessage);

    this.determineUser();
  }



  /**
   * When a user joins the chatroom, check if they are an existing user.
   * If they aren't, then ask the server for a userId.
   * Set the userId to the component's state.
   */
  determineUser() {
    AsyncStorage.getItem(USER_ID)
      .then((userId) => {
        // If there isn't a stored userId, then fetch one from the server.
        if (!userId) {
          this.socket.emit('userJoined', null);
          this.socket.on('userJoined', (userId) => {
            AsyncStorage.setItem(USER_ID, userId);
            this.setState({ userId });
          });
        } else {
          this.socket.emit('userJoined', userId);
          this.setState({ userId });
        }
      })
      .catch((e) => alert(e));
  }

  // Event listeners
  /**
   * When the server sends a message to this.
   */
  onReceivedMessage(messages) {
    this._storeMessages(messages);
  }

  /**
   * When a message is sent, send the message to the server
   * and store it in this component's state.
   */
  onSend(messages=[]) {
    this.socket.emit('message', messages[0]);
    this._storeMessages(messages);
  }

  render() {
    var user = { _id: this.state.userId || -1 };

    return (
<></>
    );
  }


}

Upvotes: 1

Dirk
Dirk

Reputation: 3391

I also wanted to use Socket.IO with ExpressJS server and React Native but couldn't get it to work.

Then used https://facebook.github.io/react-native/docs/network.html#websocket-support with https://github.com/websockets/ws

And works great.

Upvotes: 2

Related Questions