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

225
Vistas
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 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