Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 441
modernator Avatar asked Sep 27 '16 14:09

modernator


1 Answers

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>
        );
    }
}
like image 145
derek.z Avatar answered Sep 28 '22 05:09

derek.z