React Native 与 WebSocket 不起作用 [英] React Native with WebSocket doesn't work

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

问题描述

我听说 Socket.io 在 React Native 中不能正常工作,所以我决定改用普通的 WebSocket.

I heard that Socket.io not worked properly in React Native, so I decided to use plain WebSocket instead.

我正在使用 node.js 来实现 WebSocket 服务器,这并不难.使用浏览器,我尝试的所有方法都有效,但使用 React Native,没有成功.

I'm using node.js for implemeting WebSocket server, and it wasn't hard. With browsers, all of I tried worked, but with React native, none of success.

这些是我尝试实现 websocket 服务器的方法:

These are what I tried for implementing websocket server:

  • express-ws
  • ws

express-ws 在没有任何错误消息的情况下无法正常工作.只是说连接失败.

express-ws was just not worked without any error message. Just it saids failed to connect something.

所以我把模块改成了ws,这个模块应该是客户端和服务器都需要的,所以我做了.服务器已工作,但是在 AVD 上使用 android 的应用程序中时,它说:

So I changed the module to ws, and this module should be required both client and server, so I did. Server was worked, but when in the app with android on AVD, it saids:

需要未知模块url".如果您确定该模块在那里,尝试重新启动打包程序或运行npm install".

Requiring unknown module "url".If you are sure the module is there, try restarting the packager or running "npm install".

所以我完全删除了 node_modules 目录并重新安装它们,但同样的错误再次出现.

So I removed node_modules directory entirely and reinstall them, but same error shown up again.

我使用的是 node v6.2.2,react-native-cli 1.0.0,react-native 0.33.0.

I'm using node v6.2.2, and react-native-cli 1.0.0, react-native 0.33.0.

这是带有 ws 模块的服务器代码(与 ws 模块自述文件相同):

This is the server code with ws module(same as ws module readme):

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });

wss.on('connection', (socket) => {
    socket.on('message', (msg) => {
        console.log('Received: ' + msg);
    });

    socket.send('something');
});

这是客户:

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

const WebSocket = require('ws');

class wschat extends Component {
    constructor() {
        super();
    }
    componentDidMount() {
        var socket = new WebSocket("ws://localhost:3000");

        socket.on('open', () => {
            socket.send('something');
        });
        socket.on('message', (data, flags) => {
            console.log(data);
            console.log(flags);
        });
    }
    ...

为了避免命名冲突,我在需要 ws 模块时使用了 WebSock 而不是 WebSocket,但这没有问题.

To avoid naming conflict, I was used WebSock instead WebSocket when requiring ws module, but it wasn't problem.

有什么我错过的吗?React Native doc 没有太多解释,很难找到工作示例.感谢您的阅读,任何建议将不胜感激.

Is there a something that I missed? React Native doc has not much explanations, and it is hard to find working examples. Thanks for reading, and any advice will very appreciate it.

推荐答案

最新的react native支持websocket,所以我们不必依赖3rd party websocket client library.

The latest react native supports websocket, so we don't have to depend on 3rd party websocket client library.

以下示例基于react native 0.45,项目由create-react-native-app生成.

The following example is based on react native 0.45, and the project is generated by create-react-native-app.

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

export default class App extends React.Component {

    constructor() {
        super();

        this.state = {
            echo: ''
        };
    }

    componentDidMount() {
        var socket = new WebSocket('wss://echo.websocket.org/');

        socket.onopen = () => socket.send(new Date().toGMTString());

        socket.onmessage = ({data}) => {
            console.log(data);

            this.setState({echo: data});

            setTimeout(() => {
                socket.send(new Date().toGMTString());
            }, 3000);
        }
    }

    render() {
        return (
            <View>
                <Text>websocket echo: {this.state.echo}</Text>
            </View>
        );
    }
}

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

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