首页 > 解决方案 > Socket-io 无法在带有 React Native 和 Expo 的 Android 上运行

问题描述

在我的应用程序中,我已经通过外部服务器( https://api.xxxxx.com:300)使用 socket-io 实现了实时

目前它适用于 iOS,但 Android 永远无法连接到服务器。

在服务端,socket io 声明如下

var app = require('express')();
var fs = require('fs');
var options = {...};
var https = require('https').Server(options, app);
var io = require('socket.io')(https);
var curl = require('http');

io.on('connection', function(socket){
    ....
});

https.listen(3000, function(){
    console.log('listening on *:3000');
});

在我的 App.js 文件中,我必须使用以下代码开始连接:

  // Initialize Socket IO:


global.socket = socketIO("https://api.xxxxx.com:3000", {
    transports: ['websocket'],
    forceNew: true,
    reconnectionDelay: 3000,
    reconnection: true,
    reconnectionAttempts: Infinity,
    jsonp: false
  });

  socket.connect();

  console.warn('First', JSON.stringify(socket['io']));

  socket.on('connect', () => {
    console.warn('Connect Correctly');
  });

  console.warn('Second', JSON.stringify(socket['io']));

如您所见,我打印了套接字的状态以查看在第一秒和第二秒总是出现的 readyStatus:“opening”

稍后,我在我的应用程序中检查了套接字的状态,并出现了一个 readyStatus: closed。

我记得这只会在 Android 中发生在我身上,在 iOS 中,操作是完美的,并且总是以连接状态结束。

我在我的应用程序中拥有的版本如下:

{
  "name": "xxxxxx-app",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.2",
    "expo": "^35.0.0",
    "i18n-js": "^3.3.0",
    "json-circular-stringify": "0.0.1",
    "moment": "^2.24.0",
    "native-base": "^2.13.5",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-web": "^0.11.7",
    "react-navigation": "^3.13.0",
    "socket.io-client": "^2.1.1"
  },
  "devDependencies": {
    "babel-preset-expo": "^7.0.0"
  },
  "private": true
}

标签: javascriptreact-nativewebsocketsocket.ioexpo

解决方案


这对我有用,将其添加到客户端

const socket = io(baseUrl,{
transports: ['websocket'])}

来源:链接


推荐阅读