RabbitMQ React Native send example

早过忘川 提交于 2021-02-09 11:01:41

问题


I'm tryin to use RabbitMQ with React Native. I could'nt find an example about this topic. I've followed this great answer I've got a connection to the server from my emulator. I'm tryin to send a simple message from server with rabbitmq hello world tutorial. Message goes to queue, I can see it on the management tab on browser. I'm tryin to listen to it as react-native-rabbitmq read.me, using below code.

// Receive one message when it arrives
queue.on('message', (data) => {

});

// Receive all messages send with in a second
queue.on('messages', (data) => {

});

Not getting the message from the server. Any idea or example would be great. Thanks in advance. Cheers


回答1:


So if you are familiar with my previous post on how to connect a react-native app to a rabbitmq server link, this post answers the question on how to send messages to or control the actions of a react native app. If not, try to go through the post because I will be making reference to some details explained in the previous post.

As stated in the earlier post, the whole process was carried out on a windows 10 OS and Android OS 6.0 and above.

Access your react-native app folder on the command line and pull the following libraries individually

npm install react-native-simple-toast -–save

npm install react-native-phone-call --save

npm install amqplib -–save

--The toast library is similar to the prompt function in vanilla JS. It is meant to echo any message passed as arguments on the app screen

--The phone call library opens up the call menu and logs any number you pass as argument on the screen

Inside your react-native project folder, edit your App.js file to look like the snippet below

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import {
  Connection,
  Queue,
  Exchange
} from 'react-native-rabbitmq';
import Toast from 'react-native-simple-toast';
import call from "react-native-phone-call";

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {

  constructor(props) {
    super(props)

  }

  componentWillMount() {

    const config = {
      host: '192.168.137.1,  //your hotspot IPv4 address
      port: 5672,
      username: ‘dummy’,   //your rabbitmq management username
      password: ‘dummy’,   //your rabbitmq management password
      virtualhost: ‘/’
    };

    let connection = new Connection(config)
    connection.connect()

    let connected = false;
    let queue;
    let exchange;

    connection.on('connected', (event) => {

      queue = new Queue(connection, {
        name: '',
        passive: false,
        durable: true,

        exclusive: false,
        consumer_arguments: { 'x-priority': 1 }
      });

      exchange = new Exchange(connection, {
        name: 'direct_log',
        type: 'direct',
        durable: false,
        autoDelete: false,
        internal: false
      });

      queue.bind(exchange, 'info');

      queue.on('message', (data) => {

        if (data.message=="make-call") {
          const args = {
            number: '131',
            prompt: false
          }

          call(args).catch(console.error)

        }
        if (data.message=="alert-msg") {
          Toast.show(data.message);

        }



      });



    });

    connection.on('error', event => {

      connected = false;
      console.log(connection);
      console.log(event);
      console.log("you are not connected");
    });

  }


  render() {

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Inside the config object, your host ip can be gotten by running the following anywhere on your command line

ipconfig

Look for IPv4 Address under Wireless LAN adapter Local area connection

The port is the rabbitmq port – 5672

The username and password are those you set for your rabbitmq management <link>

Now, create a server.js file inside your root folder and paste the following code snippet

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function (err, conn) {

    conn.createChannel(function(err, ch){

        var ex = "direct_log";
        var msg = process.argv.slice(2).join(' ')|| "hello Joshua";
        var args = process.argv.slice(2);

        ch.assertExchange(ex, 'direct', {durable:false})
        ch.publish(ex, 'info', new Buffer(msg));
        console.log("message sent", 'info', msg);

        setTimeout(function() {conn.close(); process.exit(0) }, 500);

    });
});

The data which will be sent to the react-native app will be initiated via the sender.js file Since the message type is a direct type only a recipient with a corresponding routing key (info is the routing key in this case). The routing key is published along with the exchange via the channel and once the queue in the App.js file is bound to the exchange along with the correct routing key, the recipient i.e. the React-Native App should be able to perform actions based on whatever message is passed.

Once everything is set up, open another terminal of your command line and run

rabbitmq-server

from anywhere on the command line start up your react-native app (via Android emulator or your Android phone). There should be no errors rendered on the screen.

Access your rabbitmq management on your browser via

host:15672  e.g  192.168.137.1:15672

Once you’re logged in, you should see a connection under the connections tab. Open yet another terminal of your command line and access the root folder of your react-native app and run the sender.js file along with a message

node sender.js alert-msg

the above command should show a pop-up message (alert-msg) on your app screen check the queues tab in your rabbitmq management, you should see incoming and outgoing data under the respective tabs. You could also send a message for the phone call with

node sender.js make-call

this should open up the call menu on the android device. Once the above methods work out, you could check out other libraries which could help You perform more functions on your android device or on the react-native app.

Cheers to the team of Interns and our Senior colleagues at Swap Space Systems. We banged our heads together for several weeks before we got to this point.



来源:https://stackoverflow.com/questions/49601914/rabbitmq-react-native-send-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!