Estoy escribiendo un proyecto vue con WebSocket. Escribo el código de WebSocket-Client en un módulo. Codifico como a continuación:
//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) }En el componente de vue, lo uso como se muestra a continuación:
import * as graphqlSocket from '@/utils/websocket' //In created(): graphqlSocket.initialClient() graphqlSocket.testHeart() En la función testHeart() , espero que reinicie la conexión cuando se cierra la conexión (ya sea que el servidor o el cliente la cierren). Pero cuando lo pruebo, el graphqlWSClient.onopen parece funcionar instantáneamente, no funciona hasta que se abre la conexión, error de lanzamiento de la consola:
state: 0 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at graphqlWSClient.onopen¿Alguien puede decirme por qué? 😢😢😢