React全局WebSocket组件

import React, { createContext, useEffect, useRef } from 'react';
import apiConfig from '@configs/servicesIP';
import { notification } from 'antd';
import { CheckCircleFilled } from '@ant-design/icons';

export const WebSocketContext = createContext(null);

export const WebSocketProvider = ({ children }) => {
  const socketRef = useRef();

  const initWebSocket = () => {
    // 创建 WebSocket 连接
    let url = '';
    if (process.env.NODE_ENV === 'development') {
      url = ‘’;
    } else {
      url = window.location.host;
    }

    socketRef.current = new WebSocket('ws://' + url + '');

    socketRef.current.onopen = () => {
      console.log('连接打开');
    };

    socketRef.current.onclose = () => {
      console.log('连接关闭');
    };

    socketRef.current.onerror = (error) => {
      console.error('连接失败:', error);
    };

    socketRef.current.onmessage = (message) => {
      console.log('推送的消息:', message?.data);
      try {
        const data = JSON.parse(message?.data);
        if (data?.status === '200') {
          notification.open({
            message: (
              <>
                <CheckCircleFilled style={{ color: 'green', marginRight: 8 }} />
                消息推送通知
              </>
            ),
          });
        }
      } catch (error) {
        console.error('JSON 解析错误:', error);
      }
    };
  };

  useEffect(() => {
    // initWebSocket();//挂载默认是否打开
    return () => {
      if (socketRef.current) {
        socketRef.current.close();
      }
    };
  }, []);

  return (
    <WebSocketContext.Provider value={{ socketRef: socketRef.current, initWebSocket }}>
      {children}
    </WebSocketContext.Provider>
  );
};

React 应用程序创建了一个 WebSocket 上下文和提供者组件,以便在应用的其他部分中共享 WebSocket 连接。这个模式非常适合处理 WebSocket 连接,尤其是在全局状态或多个组件中需要使用 WebSocket 的情况下。

以下是你代码的功能和优化建议:

功能概述

  • WebSocketContext: 使用 createContext 创建了一个上下文,用于在组件树中共享 WebSocket 连接和相关函数。
  • WebSocketProvider: 包装应用程序的提供者组件,管理 WebSocket 连接的生命周期。
    • socketRef: 使用 useRef 创建一个持久化的 WebSocket 实例引用,避免在组件重新渲染时重新创建 WebSocket 实例。
    • initWebSocket: 初始化 WebSocket 连接的函数。根据环境配置 WebSocket 的 URL,并处理连接的打开、关闭、错误和消息事件。
    • useEffect: 确保在组件卸载时关闭 WebSocket 连接,以防止内存泄漏。
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值