react-native HTTP Requests Web Socket with Socket.io


Example

Install socket.io-client

npm i socket.io-client --save

Import module

import SocketIOClient from 'socket.io-client/dist/socket.io.js'

Initialize in your constructor

constructor(props){
    super(props);
    this.socket = SocketIOClient('http://server:3000');
  }

Now in order to use your socket connection properly, you should bind your functions in constructor too. Let's assume that we have to build a simple application, which will send a ping to a server via socket after every 5 seconds (consider this as ping), and then the application will get a reply from the server. To do so, let's first create these two functions:

_sendPing(){
    //emit a dong message to socket server
    socket.emit('ding');
}

_getReply(data){
    //get reply from socket server, log it to console
    console.log('Reply from server:' + data);
}

Now, we need to bind these two functions in our constructor:

constructor(props){
    super(props);
    this.socket = SocketIOClient('http://server:3000');

    //bind the functions
    this._sendPing = this._sendPing.bind(this);
    this._getReply = this._getReply.bind(this);
}

After that, we also need to link _getReply function with the socket in order to receive the message from the socket server. To do this we need to attach our _getReply function with socket object. Add the following line to our constructor:

this.socket.on('dong', this._getReply);

Now, whenever socket server emits with the 'dong' your application will able to receive it.