You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用Socket.io读写MySQL数据是否可行?

Is using Socket.io with MySQL for friend data operations feasible?

Absolutely, this is a totally valid approach and one that’s commonly used in real-time chat applications. Socket.io acts as your real-time communication layer between the React Native client and Node.js server, while MySQL handles persistent storage of friend data—they integrate seamlessly together. Your initial example is a solid starting point; let’s expand it with complete, production-ready code for both queries and inserts, plus key best practices.

Server-Side Implementation (Node.js + Socket.io + MySQL)

First, install the MySQL client for Node.js (we’ll use mysql2 for promise support, which works better with async/await):

npm install mysql2

Next, set up a MySQL connection pool (far more scalable than a single connection) and integrate it with your Socket.io server:

const { createPool } = require('mysql2/promise');
const { Server } = require('socket.io');

// Configure MySQL connection pool
const pool = createPool({
  host: 'your-mysql-host', // e.g., localhost or a cloud DB endpoint
  user: 'your-db-username',
  password: 'your-db-password',
  database: 'chat_app_db',
  connectionLimit: 10, // Adjust based on your expected traffic
  waitForConnections: true
});

// Initialize Socket.io server with CORS enabled for React Native
const io = new Server(3000, {
  cors: {
    origin: "http://your-react-native-app-url", // Update to your app's origin
    methods: ["GET", "POST"]
  }
});

io.on('connection', async (socket) => {
  console.log(`User connected: ${socket.id}`);

  // Example 1: Fetch friend data for a logged-in user
  socket.on('fetchFriends', async (userId) => {
    try {
      // Parameterized query to prevent SQL injection
      const [friendRows] = await pool.execute(
        'SELECT f.friend_id, u.username FROM friends f JOIN users u ON f.friend_id = u.id WHERE f.user_id = ?',
        [userId]
      );
      socket.emit('getFriendDatas', friendRows);
    } catch (err) {
      console.error('Failed to fetch friends:', err);
      socket.emit('friendError', 'Could not load your friends');
    }
  });

  // Example 2: Send a friend request (insert into MySQL)
  socket.on('sendFriendRequest', async (senderId, receiverId) => {
    try {
      await pool.execute(
        'INSERT INTO friend_requests (sender_id, receiver_id, status) VALUES (?, ?, ?)',
        [senderId, receiverId, 'pending']
      );
      // Notify the receiver in real-time if they're online
      socket.to(receiverId).emit('newFriendRequest', { senderId });
      socket.emit('requestSentSuccess', true);
    } catch (err) {
      console.error('Failed to send request:', err);
      socket.emit('friendError', 'Could not send friend request');
    }
  });

  // Example 3: Accept a friend request (transaction for data consistency)
  socket.on('acceptFriendRequest', async (userId, requesterId) => {
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();
      
      // Update request status to accepted
      await connection.execute(
        'UPDATE friend_requests SET status = ? WHERE sender_id = ? AND receiver_id = ?',
        ['accepted', requesterId, userId]
      );
      
      // Insert mutual friendship into friends table
      await connection.execute(
        'INSERT INTO friends (user_id, friend_id) VALUES (?, ?), (?, ?)',
        [userId, requesterId, requesterId, userId]
      );

      await connection.commit();
      // Notify both users of the new friendship
      socket.emit('friendAdded', { friendId: requesterId });
      socket.to(requesterId).emit('friendAdded', { friendId: userId });
    } catch (err) {
      await connection.rollback();
      console.error('Failed to accept request:', err);
      socket.emit('friendError', 'Could not accept friend request');
    } finally {
      connection.release();
    }
  });

  socket.on('disconnect', () => {
    console.log(`User disconnected: ${socket.id}`);
  });
});

Client-Side Implementation (React Native)

Here’s how you’d interact with these Socket.io events in your React Native app:

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

const socket = io('http://your-server-url:3000');

const FriendsScreen = () => {
  const [friends, setFriends] = useState([]);
  const currentUserId = 'your-logged-in-user-id'; // Get from auth system

  useEffect(() => {
    // Fetch friends on component mount
    socket.emit('fetchFriends', currentUserId);

    // Listen for friend data response
    socket.on('getFriendDatas', (friendData) => {
      setFriends(friendData);
    });

    // Listen for errors
    socket.on('friendError', (message) => {
      alert(message);
    });

    // Cleanup event listeners on unmount
    return () => {
      socket.off('getFriendDatas');
      socket.off('friendError');
    };
  }, []);

  const handleSendRequest = (receiverId) => {
    socket.emit('sendFriendRequest', currentUserId, receiverId);
    socket.on('requestSentSuccess', () => {
      alert('Friend request sent!');
    });
  };

  return (
    // Your UI to display friends and send requests
    <>{/* ... */}</>
  );
};

Key Best Practices

  • Use Connection Pools: Avoid single database connections—pools handle concurrent requests efficiently and prevent connection leaks.
  • Parameterized Queries: Always use ? placeholders instead of concatenating user input to avoid SQL injection attacks.
  • Error Handling: Never ignore database errors; emit meaningful error events to the client so users get clear feedback.
  • Transactions: For multi-step operations (like accepting a friend request), use transactions to ensure data consistency—if one step fails, all changes are rolled back.
  • Authentication: Add JWT or session-based auth to verify users before allowing them to access/modify friend data (you can pass tokens when connecting to Socket.io).

内容的提问来源于stack exchange,提问作者inhoLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:36:23