Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

socket.io client making 2 connections

I’ve tried using the options mentioned on socketio’s website to increase the time before reconnection, disabling connection upgrade from http to websocket, enabling the forceNew option. But there’s always 2 connections whenever the client page loads.
Anyone has any idea on what is going on. I’m eager to give more information if required. Thank you for reading this.

Client Code( React.js + TailwindCSS )

import "./App.css";
import { io } from "socket.io-client";
import Home from "./pages/Home/Home";

function App() {
  const socket = io("http://localhost:3000/");
  socket.on("connect", () => {
    console.log(socket.id);
    console.log(socket.connected);
  });
  return (
    <div className="App">
      <Home />
    </div>
  );
}

Server Code (Node.js)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import http from "http";
import { Server } from "socket.io";
import express from "express";

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3001",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (client) => {
  console.log("client connected", client.id);
  client.on("event", (data) => {});
  client.on("disconnect", () => {});
});

server.listen(3000);
server.on("listening", () => console.log("listening"));

Client Console

2zcCMTkpbDtW-R5jAAA-
true
KdzGTWRxUIhlk0bKAAA_
true

Server Console

listening
client connected zh1zj5dnUb55zUdrAAAB
client connected rQexCoY7B6Es_r_RAAAD

Chrome console output

>Solution :

You need to initiate the socket inside a useEffect hook, otherwise, it will run each time your component rerenders.

In this case, io function will trigger only once, since the useEffect has no dependencies, it will run one time only. Also, make sure to close the connection once your App is unmounted

function App() {
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    const s = io("http://localhost:3000/");
    setSocket(s);

    return () => s.disconnect();
  }, [setSocket]);

  return (
    <div className="App">
      <Home />
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading