React Native with WebSocket不起作用

React Native with WebSocket doesn't work

本文关键字:不起作用 WebSocket with Native React      更新时间:2023-09-26

我听说插座。在React Native中不能正常工作,所以我决定使用普通的WebSocket来代替。

我使用node.js实现WebSocket服务器,这并不难。对于浏览器,我所有的尝试都有效,但对于React native,没有成功。

这些是我尝试实现websocket server:

  • express-ws
  • ws

express-ws不工作,没有任何错误消息。只是说连接失败

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

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

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

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

这是ws模块的服务器代码(与ws模块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,但这不是问题。

我错过了什么吗?React Native文档没有太多的解释,而且很难找到可行的例子。感谢您的阅读,如有任何建议,我将不胜感激。

最新的react native支持websocket,所以我们不需要依赖第三方websocket客户端库。

react native 0.45为例,工程由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文件夹上安装npm install websocket包。到相关Github仓库的链接如下

import React, { useEffect } from 'react';
import { w3cwebsocket as W3CWebSocket } from "websocket";
import { Text} from 'react-native';
var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
function App() {
    client.onopen = function() {
    console.log('WebSocket Client Connected');
      function sendNumber() {
         if (client.readyState === client.OPEN) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            client.send(number.toString());
            setTimeout(sendNumber, 1000);
         }
      }
      sendNumber();
     };
     client.onclose = function() {
       console.log('echo-protocol Client Closed');
     };
     client.onmessage = function(e) {
        if (typeof e.data === 'string') {
          console.log("Received: '" + e.data + "'");
        }
    };  
    return (
     
        <Text>Practical Intro To WebSockets.</Text>
     
    );
}
export default App;