Skip to content

Instantly share code, notes, and snippets.

@builat
Last active November 29, 2017 15:14
Show Gist options
  • Select an option

  • Save builat/40ee2601029ac230a970385147e15772 to your computer and use it in GitHub Desktop.

Select an option

Save builat/40ee2601029ac230a970385147e15772 to your computer and use it in GitHub Desktop.
import {consumeMessage} from './WsSaga'
let instance = null;
function reconnect(){
console.log('reconnecting...')
instance = null;
const reconntction = setInterval(()=>{
if( instance === null || instance._wss.readyState !== 1){
new WsProvider()
} else {
clearInterval(reconntction)
}
})
}
export default class WsProvider {
constructor(token){
//if( !token ) { return instance }
if( instance !== null ) { return instance }
console.log("New WebSocket Provider instanced")
let tuuid = token;
const ka = JSON.stringify({p_action:"keepAlive",params:{}});
if(tuuid === undefined){tuuid = localStorage.getItem('tstoken')}
if(tuuid !== null || tuuid !== undefined){
this._wss = new WebSocket(`ws://localhost:9008/ws?token=${tuuid}`)
}else{
return null
}
this._wss.onopen=(e)=>{
this._connection_ = setInterval(()=>{
if(this._wss.readyState !== 1){
clearInterval(this._connection_)
console.log("Cоnnection lost!..")
reconnect()
} else {
this._wss.send(ka)
}
}, 5000)
}
this._wss.onmessage = ( wsMsg ) => {
let msg = null
try{
msg = JSON.parse(wsMsg.data)
}catch(e){
msg = {payload:{listener: "common", data:wsMsg.data}}
}
if(msg.msg !== undefined) {
consumeMessage(msg.payload).next()
}
}
instance = this;
return instance;
}
send = e =>{
let stringifyed = null;
try{
stringifyed = JSON.stringify(e)
} catch(ex) {
throw new Error(ex)
}
this._wss.send(stringifyed)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment