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

219
Visualizações
WebSocket.onopen not work properly,it excute when connection is still connecting

I'm writing a vue project with WebSocket.I write WebSocket-Client's code in a module.I code like below:

//websocket.js
var graphqlWSClient = new WebSocket("ws://localhost:8000", "graphql-transport-ws")


function isOpened(){
    return graphqlWSClient.readyState == 1
}

export function initialClient(){
    graphqlWSClient.onopen = function (eve) {
        graphqlWSClient.send(JSON.stringify({"type":"connection_init","payload":{}}))
    }
}

//Heartbeat function to detect whether connenction working
export function testHeart(){
    setInterval(()=>{
        if(isClosed()){
            graphqlWSClient = new WebSocket("ws://localhost:8000", "graphql-transport-ws")
            graphqlWSClient.onopen = function(eve){ //!!!NOT WORK
                console.log(eve)
                console.log("state:",graphqlWSClient.readyState)
                graphqlWSClient.send(JSON.stringify({"type":"connection_init","payload":{}}))
            }
        }
        try {
            graphqlWSClient.send(JSON.stringify({"type":"ping"}))
        } catch (error) {
            console.log(error)
        }
    },3000)
}

In the vue's component,I use it like below:

import * as graphqlSocket from '@/utils/websocket'


//In created():
    graphqlSocket.initialClient()
    graphqlSocket.testHeart()

In the function testHeart(),I expect it restarts the connection when connection is closed(whether server or client close it).But when I test it,the graphqlWSClient.onopen looks working instantly,not working until the connection is opened,as the console throw error:

state: 0
       Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
    at graphqlWSClient.onopen 

Does anyone can tell me why?😢😢😢

about 4 years ago · Santiago Trujillo
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