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.

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Web Socket with Socket.io in react native

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password