React Native 与 socket.io 不起作用 [英] React Native with socket.io doesn't work

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

问题描述

我创建了一个简单的 socket.io 服务器并响应本机项目并进行了测试,但是 React Native 上的 socket.io 根本不起作用.我在控制台上打印了socket.io-client"并且它加载得很好,我使用 socket.io 制作了简单的 HTML 文件,它可以工作,但只有 React Native 不工作.我使用的是 React Native 0.26.2 和 socket.io 1.4.6.

i create simple socket.io server and react native project and tested, but socket.io on React Native doesn't work at all. i printed "socket.io-client" on console and it's loaded well, and i made simple HTML file with using socket.io, it works, but only React Native doesn't work. i'm using React native 0.26.2, and socket.io 1.4.6.

这是我的服务器代码:

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

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

http.listen(3000, () => {
    console.log('server started on 3000');
});

// web testing
app.get('/', (req, res, next) => {
    res.sendFile(__dirname + '/index.html');
});

这是 rn 代码:

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

import "./userAgent"; //window.navigator.userAgent = "react-native";

const io = require('socket.io-client/socket.io');

class SocketChat extends Component {
    constructor(props) {
        super(props);
        this.socket = io('localhost:3000', { jsonp: false });
        this.state = {
            text: null
        };
    }
    ...
}

据我所知,在 socket.io 中使用 React Native 会导致 ajax 长轮询而不是 websocket,所以我添加了用户代理"技巧.无论它是否工作,甚至没有建立连接,但如果我尝试使用浏览器,它运行良好.告诉我该怎么做,我会很感激.

as i heard, using React native with socket.io causes ajax long polling instead of websocket, so i added 'user-agent' trick. whether it is working or not, even connection isn't established, but if i try with browser, it works well. it will be very appreciate me that tell me what should i do.

推荐答案

我通过替换另一个 websocket 模块解决了这个问题.Socket.IO 在 Android 上不起作用,正如有人对我说的那样,Socket.io 在内部使用节点本机模块,因此在构建生产应用程序后它应该不起作用.

I solved this by replacing another websocket module. Socket.IO doesn't work on Android and as someone said to me, Socket.io uses node native modules internally so it should be not working after build production app.

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

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