为什么我的React-Native项目中的Socket.io仅在调试器运行时才能工作?

时间:2019-01-20 18:29:49

标签: react-native socket.io

我现在开始在React-Native中使用Socket.io,并且遇到以下问题:程序在调试器在后台运行时才可以运行,因此它也可以在一个模拟器上运行,并且如果调试器也可以运行在跑。因此,React Simulator仅在调试器运行时与服务器连接。

React App的代码:

import React, {Component} from 'react';
import {Platform, Text, View} from 'react-native';
window.navigator.userAgent = 'react-native';
//import io from 'socket.io-client/dist/socket.io';
const io = require('socket.io-client/dist/socket.io');

import styles from './styles';

class App extends Component{
  state = {
    name: 'Bob'
  }

  constructor(){
    super();

    this.socket = io('localhost:3000', {jsonp: false});

    this.socket.on('update', () => this.setState({name: 'Sonja'}));
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.name}</Text>
      </View>
    );
  }
}

export default App;

服务器代码:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    console.log(socket.id);
    socket.on('update', () => {
      console.log('update');
      io.emit('update')
  });
}); 

package.json:

{
  "name": "TestSocket",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.16.4",
    "react": "16.6.3",
    "react-native": "0.57.8",
    "socket.io": "^2.2.0",
    "socket.io-client": "^2.2.0"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.6.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

因此,如果调试器在后台运行,则一切正常,但是,如果我关闭远程调试器或在2种不同的设备上尝试代码,则将无法正常运行,或者仅对于运行调试器的设备不起作用。

先谢谢您!

2 个答案:

答案 0 :(得分:0)

Socket.io 2.2.0不能与ReactNative一起使用(请参见https://github.com/socketio/socket.io-client/issues/1254

它仅在调试器中有效,因为在调试时,JS在Chrome中运行,而不在应用程序ReactNative上下文中运行。

解决方案 =>恢复到Socket.io 2.1.1

答案 1 :(得分:0)

将RN降级到0.57.x,并尝试使用socket.io-client 2.1.1或2.0.4。