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

154
Visualizações
Reconnecting to socket channel after disconnection in react

There's various answers to this question, but either they're outdated (I don't think the "reconnect" event exist anymore?) or just doesn't work for me.

I have a ton of data that the client is waiting for from the server via socket.io sockets. It's fine until 10-15 minutes later with over 1600 results that the socket reconnects. After the reconnection happens, I do not get anymore of the data that the server emits, which I assume is because I've lost the events from the original socket connection.

I have to refresh to continue getting that data.

How do I reconnect to socket.io after every reconnection?

Client:

socket.js (context)

import { createContext } from 'react';
import io from 'socket.io-client';

export const socket = io('http://localhost:5000');

export const SocketContext = createContext();

Layout.js

import { socket, SocketContext } from '../context/socket'

function MyApp({ Component, pageProps }) {

  return <SocketContext.Provider value={socket}>
    <Layout>
      <Component {...pageProps} />
    </Layout>
  </SocketContext.Provider>
}

page (next.js)

  import { SocketContext } from '../context/socket'; 
  ...
  const socket = useContext(SocketContext);
  useEffect(() => {
    socket.emit('joined', socketChannel);
    socket.on(socketChannel, handleStream);
  }, []);

Server:

index.js (Uses fastify-socket.io)

    fastify.io.on('connection', socket => {
        socket.on('joined', (channel) => {
            socket.join(channel);
        })
    });
    redis.subscriber.on('message', (channel, message) => {
        io.to(channel).emit(channel, message);
    });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Socket.io will automatically leave the rooms when you have a disconnect.

Rooms are left automatically upon disconnection.

in useEffect(), you are joining the room once:

  socket.emit('joined', socketChannel);
  socket.on(socketChannel, handleStream);

Two options:

  1. Automatically join at connect on client:
  useEffect(() => {
    socket.on(socketChannel, handleStream);

    // connect fires when connected, also after reconnected
    socket.on('connect', () => {
      console.log('connect', socket.connected);
      // automatically join the room
      socket.emit('joined', socketChannel);
    });
  }, []);
  1. Automatically join at the server, but this assumes all clients join the relevant room which may not be suitable:
io.on('connection', (socket) => {
  console.log(`${socket.id} connected`);

  // automatically join the room
  socket.join(socketChannel);
  ...
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