一个WebSocket的自定义hook
自己封装了一个WebSocket的hook,代码如下:
import { useEffect, useRef } from "react";const WS_URL = 'wss://xxx' // 服务地址const useSocket = () => {const socketRef = useRef<WebSocket>()let heartTimer = 0; // 心跳定时器 IDconst 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 = undefinedclearInterval(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()