一个WebSocket的自定义hook

自己封装了一个WebSocket的hook,代码如下:

import { useEffect, useRef } from "react";

const WS_URL = 'wss://xxx' // 服务地址

const useSocket = () => {

const socketRef = useRef()

let heartTimer = 0; // 心跳定时器 ID

const heartCheck = (socket: WebSocket) => { // 心跳检查

clearInterval(heartTimer); // 先清除之前的定时器

heartTimer = setInterval(() => {

socket.send('xxx'); // 约定好的心跳

}, 30000);

}

const createSocket = () => { // socket创建

if (socketRef.current) return;

const socket = new WebSocket(`${WS_URL}`) // 信令服务器连接

socket.onopen = () => { // 连接建立

console.log("[ws open] 连接已建立");

heartCheck(socket);// 心跳处理

};

socket.onmessage = async (event) => { // 接收到服务器的信息

console.log(event)

};

socket.onclose = () => { // 连接关闭

console.log('[ws close] 连接中断');

socketRef.current = undefined

clearInterval(heartTimer); // 清除定时器

};

socket.onerror = (error) => { // 连接错误

console.log(`[error] 连接错误 `, error);

};

return socket;

}

useEffect(() => { // 监听房间

socketRef.current = createSocket();

// 关闭socket的方法

// socketRef.current.close();

}, [])

return socketRef; // 如果不需要的话不返回也是可以的

}

export default useSocket

使用方法如下:

const socketRef = useSocket()

相关阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 


大家都在找:

websocket:websocket和http区别

react.js:react.js百度百科