Expo react-native 不会连接到 socketio(Android and iOS)

Expo react-native will not connect to socketio(Android and iOS)

我正在尝试使用 expo 连接到 socketio,并为 ios(通过 expo app 隧道连接进行连接)和 android 使用模拟器进行 reacti-native,当我尝试与这些连接时,套接字赢了'connect 但如果我在 broswer socket connection 中打开 expo 应用程序但在移动模拟器上不能..我该怎么办? 客户端代码

import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
const io = require('socket.io-client');
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import Navigation from './navigation';
import { Provider } from 'react-redux';
import { store } from './redux/store'

export default function App() {
  const isLoadingComplete = useCachedResources();
  const [data, setData] = useState(null)

  useEffect(() => {
    const socket = io('http://localhost:5000', {

    });

    socket.on("ping", (data: any) => {
      setData(data)
    })



  }, [])
  console.log(data)
  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      <Provider store={store}>
        <SafeAreaProvider>
          <StatusBar style="dark" />
          <Navigation />
        </SafeAreaProvider>
      </Provider>
    );
  }
}

服务器代码

require("dotenv").config();
const express = require("express");
const http = require("http");
const socketIO = require('socket.io');


const app = express();



const server = http.createServer(app);

const PORT = process.env.PORT || 5000;

const io = socketIO(server);
io.on('connection', socket => {
  console.log('client connected on websocket');

  setInterval(() => {
    io.emit('ping', { data: (new Date()) / 1 });
  }, 1000);
});



server.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`));



确保您在客户端和服务器的每个部分都使用正确的版本进行连接。 查看 https://socket.io/docs/v3/client-installation/index.html 以确保您拥有正确的版本。我检查了源代码并确保我的设置正确但无法弄清楚为什么它不会 运行.

我在我的 React Native Expo 应用程序中安装了 socket.io-客户端的 4.0.1,但在服务器中只安装了 2.1.1 socket.io。一旦我在服务器上升级到 4,一切正常。

也在客户端改变

const socket = io('http://localhost:5000', {});

const socket = io('http://localhost:5000', {transports: ['websocket']});