wesocket配置-react hook
作者:互联网
const ws:{current:any} = useRef(null)
const [socketState,setSocketState] = useState(0)
const createSocket = () => {
// const stateArr = [
// { key: 0, value: '正在链接中' },
// { key: 1, value: '已经链接并且可以通讯' },
// { key: 2, value: '连接正在关闭' },
// { key: 3, value: '连接已关闭或者没有链接成功' }
// ]
try{
ws.current = new WebSocket(`${ window.location.protocol === 'https:' ? 'wss' : 'ws'}://222.128.58.239:18001/receive`)
console.log(ws.current)
ws.current.onopen = (e:any) => {
setSocketState(ws.current.readyState)
console.log("open",ws.current.readyState)
}
ws.current.onmessage = (msg:any) => {
const _r = JSON.parse(msg.data || JSON.stringify({}))
if(_r.hasOwnProperty("block_number")){
setBlockData(_r)
}else{
setAddressData(_r)
}
}
ws.current.onclose = (e:any) => {
setSocketState(ws.current.readyState)
console.log("close",ws.current.readyState)
}
ws.current.onerror = (e:any) => {
setSocketState(ws.current.readyState)
console.log("error",ws.current.readyState)
}
}catch(e){
console.log(e)
}
}
const closeWebSocket = () => {
console.log("close by me")
ws.current?.close()
}
useEffect(() => {
const webSocketInit = () => {
if (!ws.current || ws.current.readyState === 3) {
createSocket()
}
}
webSocketInit()
return () => {
ws.current?.close()
}
},[])
useEffect(() => {
const reconnect = () => {
console.log("reconnect")
try {
closeWebSocket()
// ws.current = null
createSocket()
} catch (e) {
console.log(e)
}
}
if(socketState===3){
reconnect()
}
},[socketState])
标签:current,readyState,const,log,wesocket,react,hook,ws,console 来源: https://www.cnblogs.com/ff2011/p/15753316.html