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

240
Visualizações
Express.js websocket server crashes when I refresh my browser

I have a simple Express.js app which starts a websocket server and then the front-end connects to this server. When I start both the back-end Express.js server and the front-end server, everything works fine and I can see the incoming messages from the back-end being logged in the front-end each second.

However, when I refresh my browser, the Express.js server crashes and logs this:

Error: WebSocket is not open: readyState 3 (CLOSED)

The Express.js code looks like this:

    import * as WebSocket from 'ws';
    const wss = new WebSocket.Server({ server });
    
    const connect = function () {
        const wss = new WebSocket.Server({ server });
        wss.on('connection', (ws) => {
            ws.send(createMessage());
    
            setInterval(() => {
                ws.send(generateMsg());
            }, 1000);
    
            ws.on('error', (err) => {
                console.warn(`Client disconnected - reason: ${err}`);
                setTimeout(() => {
                    connect();
                }, 1000)
            })
        });
    }
    
    connect();

And in my front-end, I have this:

private subject = webSocket("ws://localhost:8999");

connect() {
    this.subject.subscribe(
      (msg) => {
        console.log(msg);
      },
      err => {
        setTimeout(() => {
          this.connect();
        }, 1000)
      },
      () => console.log('complete')
    );
  }

connect();

Any ideas why the reconnection between the front-end and the back-end doesn't work?

about 4 years ago · Juan Pablo Isaza
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