【问题标题】:Expo react-native will not connect to socketio(Android and iOS)Expo react-native 将无法连接到 socketio(Android 和 iOS)
【发布时间】:2021-08-10 01:40:04
【问题描述】:

我正在尝试使用 expo 连接到 socketio,并为 ios(通过 expo 应用程序隧道连接连接)和带有模拟器的 android 连接,当我尝试与这些连接时,套接字将无法连接,但如果我打开 expo 应用程序在 broswer 套接字连接有效,但在移动模拟器上无效.. 我该怎么办? 客户端代码

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}`));



【问题讨论】:

  • 您正在尝试连接到本地主机:'http://localhost:5000' - 这将指向您的手机。改用网络 ip

标签: node.js react-native socket.io expo


【解决方案1】:

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

我在我的 react native expo 应用程序中安装了 4.0.1 的 socket.io-client,但在服务器中只安装了 2.1.1 的 socket.io。一旦我在服务器上升级到 4,一切正常。

同样在客户端改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多