WebSockets in Chrome and Firefox Disconnecting After One Minute of Inactivity

前端 未结 4 1756
陌清茗
陌清茗 2021-02-07 04:08

I have found that WebSockets in Chrome and Firefox disconnect after exactly one minute of inactivity. Based on stuff I\'ve seen online, I was all set to blame proxies or some s

4条回答
  •  感情败类
    2021-02-07 04:24

    Maybe not a clean solution but this is how I implemented websocket in JS to automatically reconnect when disconnected

    var socket_main
    const mainSocketMessageListener = (event) => {
      //retreive the data here
      console.log(event.data)
    }
    
    const mainSocketOpenListener = (event) => {
      console.log("Websocket opened")
      //Example of sending message to websocket here
      socket_main.send(JSON.stringify({
        event: "subscribe",
        data: ["all"]
      }))
    }
    
    const mainSocketCloseListener = (event) => {
      if (socket_main) {
        console.error('Websocket disconnected.')
      }
      socket_main = new WebSocket('wss://ws.example.com')
      socket_main.addEventListener('open', mainSocketOpenListener)
      socket_main.addEventListener('message', mainSocketMessageListener)
      socket_main.addEventListener('close', mainSocketCloseListener)
    }
    
    //connect the first time
    mainSocketCloseListener()
    

提交回复
热议问题