当前位置:首页 > React

react websocket 实现

2026-01-26 11:46:45React

使用 React 实现 WebSocket 连接

在 React 中实现 WebSocket 连接可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种方法的详细实现方式。

原生 WebSocket API 实现

原生 WebSocket API 是浏览器内置的功能,无需额外安装库。

react websocket 实现

import React, { useState, useEffect } from 'react';

const WebSocketComponent = () => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    // 创建 WebSocket 连接
    const ws = new WebSocket('ws://your-websocket-server-url');

    ws.onopen = () => {
      console.log('WebSocket 连接已建立');
      setSocket(ws);
    };

    ws.onmessage = (event) => {
      const newMessage = event.data;
      setMessages((prev) => [...prev, newMessage]);
    };

    ws.onclose = () => {
      console.log('WebSocket 连接已关闭');
    };

    ws.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };

    // 清理函数,组件卸载时关闭连接
    return () => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.close();
      }
    };
  }, []);

  const sendMessage = () => {
    if (socket && input) {
      socket.send(input);
      setInput('');
    }
  };

  return (
    <div>
      <h3>消息列表</h3>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button onClick={sendMessage}>发送</button>
    </div>
  );
};

export default WebSocketComponent;

使用 socket.io-client 实现

socket.io-client 是一个流行的 WebSocket 库,支持更多功能(如自动重连、事件命名等)。

react websocket 实现

安装依赖:

npm install socket.io-client

实现代码:

import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';

const SocketIOComponent = () => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    // 创建 Socket.io 连接
    const newSocket = io('http://your-socketio-server-url');

    newSocket.on('connect', () => {
      console.log('Socket.io 连接已建立');
      setSocket(newSocket);
    });

    newSocket.on('chat message', (msg) => {
      setMessages((prev) => [...prev, msg]);
    });

    newSocket.on('disconnect', () => {
      console.log('Socket.io 连接已关闭');
    });

    // 清理函数
    return () => {
      newSocket.disconnect();
    };
  }, []);

  const sendMessage = () => {
    if (socket && input) {
      socket.emit('chat message', input);
      setInput('');
    }
  };

  return (
    <div>
      <h3>消息列表</h3>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button onClick={sendMessage}>发送</button>
    </div>
  );
};

export default SocketIOComponent;

关键注意事项

  • 连接管理:确保在组件卸载时关闭 WebSocket 连接,避免内存泄漏。
  • 错误处理:监听 onerror 事件以处理连接异常。
  • 重连逻辑:原生 WebSocket 需手动实现重连,而 socket.io-client 内置自动重连功能。
  • 服务端兼容性:确保服务端协议与客户端匹配(如原生 WebSocket 或 Socket.io)。

以上两种方法均可实现实时通信,选择取决于项目需求和服务端支持情况。

标签: reactwebsocket
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

vue实现websocket

vue实现websocket

Vue 实现 WebSocket 连接 在 Vue 项目中实现 WebSocket 连接,可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种方…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react 如何跳转

react 如何跳转

使用 React Router 进行页面跳转 React 应用中通常使用 react-router-dom 库实现页面跳转。以下是几种常见的跳转方式: 安装依赖 npm install react…

react如何下载

react如何下载

安装 React 的步骤 通过 npm 或 yarn 安装 React,确保已安装 Node.js(版本建议 ≥ 14.0.0)。打开终端或命令行工具,运行以下命令: npx create-reac…