React with Socket.io-client[version: 2.1.1] could not able to connect socket.io[1.2.1]

32 Views Asked by At

I have created a React App using socket.io-client package of version 2.1.1 and in node side I have used socket.io package of version 1.2.1.

While I was trying to hit the backend using React application on browser it could not connect the socket.io of backend automatically. I have to hit the backend socket.io base URL explicitly on browser then and only then I could be able to connect the handshake connection of socket.io.

Here for the real-time testing I have used the ngrok.

Here is my Socket.io Initial setup as well as socket.io-client setup.

import { useEffect, useState } from 'react';
// import { useDispatch, useSelector } from 'react-redux';
import io from 'socket.io-client';
// import { setSocket } from '../redux/feature/userSlice';

const useSocket = (serverUrl) => {
  const [socket, setSocket] = useState(null);
  useEffect(() => {
    // Create a new Socket.io instance
    // const newSocket = io(serverUrl);
    const newSocket = io(serverUrl, {
      transports: ["websocket"],
    });
  

    // Save the socket instance to the state
    setSocket(newSocket);
    console.log("serverUrl:", serverUrl);
    console.log("newSocket:", newSocket);

    // Clean up on unmount
    return () => {
      newSocket.disconnect();
    };
  }, [serverUrl]);

  return socket;
};

export default useSocket;

import useSocket from "../../services/socket";

const socket = useSocket(finalBaseUrl);

`useEffect(() => { // Check if the socket is available if (socket) { // Set up event listeners or any other socket-related logic here // Example: Listen for 'connect' and 'disconnect' events socket.on("connect", () => { console.log("Connected to server ==>", socket); });

  socket.on("PONG", (data) => {
    console.log("PING", data);
  });

  socket.on("connect_error", (err) => {
    console.log(`connect_error due to ::::::`, err);
  });

  socket.on("disconnect", () => {
    console.log("Disconnected from server", socket);
  });
}

// Clean up on component unmount
return () => {

  if (socket) {
    socket.disconnect();
  }
};

}, [socket]);`

I have tried to change version of socket.io-client to compatible of socket.io version. But it will throw this error mentioned below. enter image description here

0

There are 0 best solutions below