【问题标题】:React Native with socket.io doesn't work使用 socket.io 反应本机不起作用
【发布时间】:2016-05-29 02:44:45
【问题描述】:

我创建了简单的 socket.io 服务器并对本机项目做出反应并进行了测试,但是 React Native 上的 socket.io 根本不起作用。 我在控制台上打印了“socket.io-client”,它加载得很好,我使用 socket.io 制作了简单的 HTML 文件,它可以工作,但只有 React Native 不起作用。 我正在使用 React 本机 0.26.2 和 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,所以我添加了“用户代理”技巧。无论它是否工作,甚至连接都没有建立,但如果我尝试使用浏览器,它工作得很好。非常感谢我告诉我该怎么做。

【问题讨论】:

  • 我还用'ws'模块创建了websocket服务器,并将代码更改为直接使用websocket(react-native官方支持),要么不工作。
  • 我刚刚在 iOS 上检查过,它工作正常。所以我在我的 android 设备(不是虚拟设备)上进行了测试,它没有用。我认为有一个问题。任何建议将不胜感激。

标签: socket.io react-native


【解决方案1】:

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

【讨论】:

  • 还是这样吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 2016-07-20
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多