Praduman Raparia
Praduman Raparia

Reputation: 131

How to import and Connect and listen to a web socket in React Native

In the onMasterClicked method I want to connect and send data to server with a web-socket.

I would prefer to use native web socket library from react-native, I can also use socket.io client but that was not working for me. I do not need server side code in the app, server is cloud.

Just want to know how to connect to server with a web-socket and send data, and listens to it when ever it sends data to the application

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';

class MasterCard extends Component {

     getMasterUnit() {
        return this.props.masterUnit;
    }

    masterClicked() {
        const cardNav = this.props.masterCardNav;

        this.props.onMasterClicked(this.getMasterUnit());

        cardNav('Room', {
            id: this.getMasterUnit().id,
            title: this.getMasterUnit().title,
        });
    }

    render() {

        return (
        <TouchableOpacity onPress={this.masterClicked.bind(this)}>
        <Card>
        <View style={styles.parentContainer}>
        <Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
        <Text style={styles.arrowTextStyle}> > </Text>
        </View>
        </Card>
        </TouchableOpacity>
        );
    }
}

const styles = {

    parentContainer: {
        flexDirection: 'row', 
        flex: 1,
        alignItems: 'center',
        height: 50
    },

    masterNameTextStyle: {
        flex: 1,
        textAlign: 'left',
        color: '#000000',
        fontSize: 16, 
        textAlignVertical: 'center'
    }, 

    arrowTextStyle: {
        flex: 1,
        textAlign: 'right',
        color: '#000000',
        fontSize: 16, 
        textAlignVertical: 'center'
    }
};

export default connect(null, { onMasterClicked })(MasterCard);

Upvotes: 0

Views: 4889

Answers (2)

Garrett McCullough
Garrett McCullough

Reputation: 980

Here's how I did it:

  1. I created a WSService.js file to contain all of the web socket logic. That file just had a class in it with a constructor that set up all of the listeners:

    class WSService {
        constructor() {
            this.ws = new WebSocket('ws://localhost:3001');
    
            this.ws.onopen = (arg) => {
                // connection opened
            };
            this.ws.onmessage = (e) => {
                // a message was received
            };
            this.ws.onerror = (e) => {
                // an error occurred
            };
            this.ws.onclose = this.logout; // function implemented elsewhere
        }
    }    
    export default new WSService();
    

Note how it instantiates the service at the bottom and exports it.

The class contained additional functions that could be used by the actions to send specific messages (for logging in or out, for example).

  1. I'm using Redux so I imported that into my actions file:

    import WSService from '../services/WSService';

  2. My actions call the service as necessary. The service also has access to the store so it dispatches actions when it receives messages.

Overall, it was much easier than I anticipated.

Full code here: https://github.com/SpaceAppsReno/higher-ground/tree/master/controller

Upvotes: 2

Train
Train

Reputation: 3516

If you look at Face books simple example you can see that react-native supports web sockets. You can also look at this for more info. Web Sockets It doesn't get any easier than that. Note that since WebSocket is global you don't need to import anything.

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

Upvotes: 1

Related Questions