From 61523ca4d0eb3a718e9b029bd3e121f3b539b3b1 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 30 Jun 2018 23:31:03 +0300 Subject: WebSockets --- vnext/src/index.js | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) (limited to 'vnext/src/index.js') diff --git a/vnext/src/index.js b/vnext/src/index.js index 2bade756..1eb01eae 100644 --- a/vnext/src/index.js +++ b/vnext/src/index.js @@ -23,7 +23,7 @@ class App extends React.Component { super(props); let params = qs.parse(window.location.search) if (params.hash) { - localStorage.visitor = JSON.stringify({uid: 0, hash: params.hash}); + localStorage.visitor = JSON.stringify({ uid: 0, hash: params.hash }); window.history.replaceState({}, document.title, `${window.location.protocol}//${window.location.host}${window.location.pathname}`) } this.state = { @@ -32,10 +32,58 @@ class App extends React.Component { hash: params.hash || '' } }; + this.pm = React.createRef(); + this.thread = React.createRef(); + } + + initWS = () => { + const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const params = { hash: this.state.visitor.hash }; + let url = `${proto}//api.juick.com/ws/?${qs.stringify(params)}`; + this.ws = new WebSocket(url); + this.ws.onopen = () => { + console.log("online"); + } + this.ws.onclose = () => { + console.log('offline'); + this.ws = false; + setTimeout(function () { + this.initWS(); + }, 2000); + } + this.ws.onmessage = (msg) => { + if (msg.data == ' ') { + this.ws.send(' '); + } else { + try { + var jsonMsg = JSON.parse(msg.data); + console.log('data: ' + msg.data); + if (jsonMsg.service) { + return; + } + if (!jsonMsg.mid) { + this.pm.current.onMessage(jsonMsg); + } + if (jsonMsg.rid && this.thread.current) { + this.thread.current.onReply(jsonMsg); + } + } catch (err) { + console.log(err); + } + } + }; + setInterval(this.wsSendKeepAlive, 90000); + } + + wsSendKeepAlive = () => { + if (this.ws) { + this.ws.send(' '); + } } componentDidMount() { - const {hash, uid} = this.state.visitor; + const { hash, uid } = this.state.visitor; + this.initWS(); if (uid === 0 && hash) { me().then(visitor => this.auth(visitor)) } @@ -92,10 +140,10 @@ class App extends React.Component { } /> } /> } /> - } /> + } /> } /> } /> - } /> + } />