Socket.io 不适用于 Android 上的 React Native [英] Socket.io not working with React Native on Android

查看:43
本文介绍了Socket.io 不适用于 Android 上的 React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在学习 React Native,在使用 Socket.IO 时遇到了问题.我正在使用最新的 React Native 和 cli(刚刚更新),这是我的代码:

I'm learning React Native recently, and having trouble with using Socket.IO. I'm using latest React native and cli(just updated), and this is my code:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

window.navigator.userAgent = 'react-native';

const io = require('socket.io-client/socket.io');
const socket = io('localhost:3000', { jsonp: false });
socket.connect();

class wschat extends Component { ... }

可以看到,代码很简单,没有错误.这是我的服务器代码:

You can see, the code is quite simple, and no error. This is my server code:

"use strict";
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

http.listen(3000, () => {
    console.log('WSChat Server for React-Native listening on port 3000');
});

io.on('connection', (socket) => {
    console.log('connected: ' + socket.id);
});

看起来不错,它实际上适用于 ios,但不适用于 android.我启用了远程调试器,并检查了属性,并且 Socket.IO 它自己加载良好,但没有建立连接.你可以看到服务器代码,当'connection'事件发生时,登录控制台.

Seems fine, and it is actually worked with ios, but not worked on android. I was enabled remote debugger, and checked the properties, and Socket.IO it self it was loaded well, but no connection was established. You can see the server code, when 'connection' event occured, logged on console.

我使用了 AVD(nexus5) 和我的设备 (LG G4 optimus),但两者都不起作用.我错过了什么?任何建议将不胜感激!

I used AVD(nexus5) and my device(LG G4 optimus), but both won't worked. What am I missing? Any advice will be very appreciate it!

推荐答案

运行的 VM react-native 不是 nodejs.这意味着您不能依赖诸如 socket.io-client 之类的包,而后者又依赖于 nodejs 原生模块(httpfscrypto 等)

The VM react-native runs in isn't nodejs. This means you can't rely on packages such as socket.io-client that in turn rely on nodejs native modules (http, fs, crypto, etc)

即socket.io-client 依赖于 engine-i.o,你会在那里找到类似的东西:

I.e. socket.io-client relies on engine-i.o and there you will find stuff like:

var http = require('http');

狡猾的是,只要你处于开发模式,iOS 就由 nodejs 支持,所以它可能看起来一切正常,但如果你编译应用程序,它就不会'

What's devious is that as long as you're in dev-mode, iOS is backed by nodejs, so it may look like all is working, but if you compile the app, it won't.

遗憾地查看 react-native-socketio(截至 2016 年 -09-12) 项目维护得不好,但可以运行.

Check out react-native-socketio, sadly (as of 2016-09-12) the project isn't well maintained, but it can be made to work.

这篇关于Socket.io 不适用于 Android 上的 React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆