我想与服务器建立网络套接字连接。如果连接关闭,则在 5 秒后重新连接。我正在使用 React Hooks,到目前为止实现了这一目标
import React, { useRef, useState, useEffect } from 'react';`
import './App.css';
function App() {
const wsClient = useRef(null);
const [wsState, setWsState] = useState(true)
useEffect(() => {
wsClient.current = new WebSocket(url);
console.log("Trying to open ws");
setWsState(true)
wsClient.current.onopen = () => {
console.log('ws opened');
wsClient.current.send('{"type" : "hello"}')
};
wsClient.current.onclose = (event) => {
// Parse event code and log
setTimeout(() => {setWsState(false)}, 5000)
console.log('ws closed');
}
wsClient.current.onmessage = ((event) => {
// DO YOUR JOB
})
return …Run Code Online (Sandbox Code Playgroud)