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?😢😢😢