DEV Community

Ajmal Hasan
Ajmal Hasan

Posted on

React Native Socket.io

Socket.IO is a JavaScript library for real-time web applications that enables real-time communication between clients and servers.

1. Install the Socket.io client library using npm or yarn:

npm install socket.io-client
# or
yarn add socket.io-client
Enter fullscreen mode Exit fullscreen mode

2. Make socket provider (socket.js):

/**
 * Socket Provider
 */
import React, {useEffect, useRef} from 'react';
import socketIOClient from 'socket.io-client';
import {ANDROID, IOS} from '../constants/constants';
import {isIOS} from '../helper';

const SOCKET_DEV = 'https://socket-dev.com';

export const SocketContext = React.createContext({socket: null});

/**
 * connectionConfig
 */
const connectionConfig = {
  jsonp: false,
  reconnection: true,
  reconnectionDelay: 100,
  reconnectionAttempts: 100000,
  transports: ['websocket'],

//optional
  query: {
    source: 'auction:mobile',
    platform: isIOS() ? IOS : ANDROID,
  },

};

/**
 * SocketProvider
 * @param {*} param0
 * @returns
 */
export const SocketProvider = ({children}) => {
  const env = SOCKET_DEV;
  const socket = useRef(socketIOClient(env, connectionConfig));

  useEffect(() => {
    socket.current.on('connect', () => {});

    socket.current.on('disconnect', msg => {
      console.log('SocketIO: Disconnect', msg);
      socket.current = socketIOClient(env, connectionConfig);
    });

    return () => {
      if (socket && socket.current) {
        socket?.current?.removeAllListeners();
        socket?.current?.close();
      }
    };
  }, [env]);

  return (
    <SocketContext.Provider value={{socket: socket.current}}>
      {children}
    </SocketContext.Provider>
  );
};

Enter fullscreen mode Exit fullscreen mode

3. Wrap App.js or any stack as per use-case with SocketProvider:

/**
 * App
 */
import React, {useEffect, useRef, useState} from 'react';
import {Provider, useDispatch} from 'react-redux';

/**
 * RootWrapper
 * @returns
 */
const RootWrapper = () => {
  return (
          <SocketProvider> //Wrap like This
            <App />
          </SocketProvider>
  );
};

export default RootWrapper;
Enter fullscreen mode Exit fullscreen mode

4. Usage in the component

Use the socket to send and receive events, also remember to clean up the Socket.io client when your component unmounts:

Before code lets understand, what is socket.io and socket.emit.

socket.on and socket.emit are two methods provided by the Socket.IO library for real-time communication between clients and servers.

socket.on(event, callback) is used to listen for incoming events from the server. When the server emits an event with the same name as the one specified in event, the client will trigger the callback function and pass any data sent by the server as an argument to the callback. For example, in the following code snippet, the client is listening for an event named message from the server:

socket.on('message', (data) => {
  console.log(`Received message: ${data}`);
});
Enter fullscreen mode Exit fullscreen mode

In this case, the client will log the message received from the server whenever the server emits a message event.

socket.emit(event, data, callback) is used to send an event to the server with optional data and an optional acknowledgement callback function. The server can listen for these events and handle them appropriately. For example, in the following code snippet, the client is emitting a message event to the server with a message payload:

socket.emit('message', 'Hello server!');
Enter fullscreen mode Exit fullscreen mode

In this case, the server can listen for the message event and handle the message appropriately. Additionally, the client can provide an optional callback function as the third parameter to receive an acknowledgement from the server when the event is received.

These two methods are the main building blocks for real-time communication between a Socket.IO client and server, allowing for bidirectional communication between the two.


For Example:

//import
import {SocketContext} from './socket';

const SocketComponentTest =()=>{

//Create Instance/Initialise
const {socket} = useContext(SocketContext);


//Use the socket to send and receive events, also remember to clean up the Socket.io client when your component unmounts:

useEffect(() => {
    InteractionManager.runAfterInteractions(() => {

      socket.emit('auction:room', {auctionId: mongoAuctionId}); //opening particular auction room 

      socket.on('bid:create', response => {
        setTimeout(() => {
          addItemToAuctionHistoryDetail &&
            addItemToAuctionHistoryDetail(response);
        }, 1000);
      });

      socket.on('auction:extended', response => {
        setTimeout(() => {
          auctionTimeExtendedSocket && auctionTimeExtendedSocket(response);
        }, 1000);
      });

      socket.on('disconnect', msg => {
        socket.emit('auction:room', {auctionId: mongoAuctionId});
      });

      socket.on('connect_error', msg => {
        socket.emit('auction:room', {auctionId: mongoAuctionId});
      });

      socket.on('reconnect', msg => {
        socket.emit('auction:room', {auctionId: mongoAuctionId});
      });
    });
    // Remove all the listeners and
    return () => {
      socket.emit('auction:leave', {auctionId: mongoAuctionId}); //closing current particular auction room
      socket.removeAllListeners();
    };
  }, []);

return </>
}

export default SocketComponentTest;
Enter fullscreen mode Exit fullscreen mode

Note:
Always remember not to create/on multiple same socket connection on any screen unless you have closed the previous same connection.

Top comments (0)