Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda