Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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)

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda