Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!