简体   繁体   中英

React Native with WebSocket doesn't work

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

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.

These are what I tried for implementing websocket server:

  • express-ws
  • ws

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

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:

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

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

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

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');
});

This is client:

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);
        });
    }
    ...

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

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.

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

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>
        );
    }
}

Install this package npm install websocket on your react native folder. The link to the relevant Github repo is this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM