简体   繁体   中英

How I can use my own broker with tcp:// uri in my react-native app?

This may sound duplicated, but it's not. I'm kinda newbie in React-Native. I'm trying to write an MQTT-Client app, making use of "react-native-paho-mqtt" library, which should be able to connect to my own broker with this uri: tcp://217.218.171.92:1883 but apparently the uri must be started with "wss" only!!! How can I make my app use tcp:// ? above that, is it possible??

here is my App.js:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  TextInput,
  Button
} from 'react-native';

import { Client, Message } from 'react-native-paho-mqtt';

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

export default class App extends Component<{}> {
  constructor(){
    super();
    const myStorage = {
      setItem: (key, item) => {
        myStorage[key] = item;
      },
      getItem: (key) => myStorage[key],
      removeItem: (key) => {
        delete myStorage[key];
      },
    };


    const client = new Client({ uri: "wss://m12.cloudmqtt.com:31839/", clientId: 'clientIdReactNative' + (new Date()).getTime(), storage: myStorage });
    client.on('messageReceived', (entry) => {
      console.log(entry);

      this.setState({message: [...this.state.message, entry.payloadString]});
    });

    client.on('connectionLost', (responseObject) => {
      if (responseObject.errorCode !== 0) {
        console.log(responseObject.errorMessage);
        this.setState({error: 'Lost Connection', isConnected: false});
      }
    });
    this.connect(client)
        .then(() => {
          console.log('connect!');
          this.setState({isConnected: true, error: ''})
        })
        .catch((error)=> {
          console.log(error);
        });


    this.state = {
      client,
      message: [''],
      messageToSend:'',
      isConnected: false
    }
  }

  connect(client){
    return client.connect({
      useSSL: true,
      userName: 'azebvdny',
      password: 'MsULac9Uhig0'
    })
    .then(() => {
      client.subscribe('S/ReactMQTT');
    })

  }

  onConnect = () => {
    const { client } = this.state;
    client.subscribe('ReactMQTT');
    this.pushText('connected');
  };
  pushText = entry => {
    const { message } = this.state;
    this.setState({ message: [...message, entry] });
  };

  onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"+responseObject.errorMessage);
    }
  }

  onMessageArrived(message) {
    console.log("onMessageArrived:"+message.payloadString);
  }

  componentWillMount(){

  }
  sendMessage(){
    var message = new Message(this.state.messageToSend);
    message.destinationName = "S/ReactMQTT";

    if(this.state.isConnected){
      this.state.client.send(message);
    }else{
      this.connect(this.state.client)
        .then(() => {
          console.log('connect!');
          this.state.client.send(message);
          this.setState({error: '', isConnected: true});
        })
        .catch((error)=> {
          console.log(error);
          this.setState({error: error});
        });

    }

  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Nativess!
        </Text>
        <Text style={styles.instructions}>
          Message: {this.state.message.join(' --- ')}
        </Text>
        <Text style={{color: 'red'}}>
          {this.state.error}
        </Text>
        { this.state.isConnected ?
            <Text style={{color: 'green'}}>
              Connected
            </Text> : null
        }
        <TextInput
          value={this.state.messageToSend} 
          onChangeText={(value => this.setState({messageToSend: value}))} 
          placeholder="Type here... "
          style={styles.input} />
        <Button onPress={this.sendMessage.bind(this)} title="Send Message" />

      </View>
    );
  }
}

const styles = StyleSheet.create({
  ...
});

Any help would be greatly appreciated.

react-native-paho-mqtt only supports WebSocket .

because react-native-paho-mqtt doesn't support raw TCP out of the box

If you use real-native-tcp to configure the client , it may be possible on the code.

The example of a module tells us it's not possible.

  test('should fail to create a new client with an invalid ws uri', function () {
    let client = null;
    let error;
    try {
      client = new Client({ uri: 'http://example.com', clientId: 'testclientid', webSocket, storage });
    } catch (err) {
      error = err;
    }
    expect(client).toBe(null);
    expect(error).not.toBe(null);

For new googlers: you can use react_native_mqt. After you managed to properly install the library, for example, this could be your App.js:

import React, { Component } from 'react';
import init from 'react_native_mqtt';
import { AsyncStorage,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  Alert
 } from 'react-native';

init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  sync: {},
});


export default class App extends Component {

  constructor(){
    super();
    this.onMessageArrived = this.onMessageArrived.bind(this)
    this.onConnectionLost = this.onConnectionLost.bind(this)


    const client = new Paho.MQTT.Client('yourURL', yourPort, 'someClientID',);
    client.onMessageArrived = this.onMessageArrived;
    client.onConnectionLost = this.onConnectionLost;
    client.connect({ 
      onSuccess: this.onConnect,
      useSSL: false ,
      userName: 'yourUser',
      password: 'yourPass',
      onFailure: (e) => {console.log("here is the error" , e); }

    });

    this.state = {
      message: [''],
      client,
      messageToSend:'',
      isConnected: false,
    };

  }


  onMessageArrived(entry) {
    console.log("onMessageArrived:"+message.payloadString);
    this.setState({message: [...this.state.message, entry.payloadString]});

  }


  onConnect = () => {
    const { client } = this.state;
    console.log("Connected!!!!");
    client.subscribe('hello/world');
    this.setState({isConnected: true, error: ''})
  };


  sendMessage(){
    message = new Paho.MQTT.Message(this.state.messageToSend);
    message.destinationName = "hello/world";

    if(this.state.isConnected){
      this.state.client.send(message);    
    }else{
      this.connect(this.state.client)
        .then(() => {
          this.state.client.send(message);
          this.setState({error: '', isConnected: true});
        })
        .catch((error)=> {
          console.log(error);
          this.setState({error: error});
        });
  }
  }


  onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"+responseObject.errorMessage);
      this.setState({error: 'Lost Connection', isConnected: false});
    }
  }




  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.welcome}>
          Welcome to React Native MQTT!
        </Text>
        <Text style={styles.instructions}>
          Message: {this.state.message.join(' --- ')}
        </Text>
        <Text style={{color: 'red'}}>
          {this.state.error}
        </Text>
        { this.state.isConnected ?
            <Text style={{color: 'green'}}>
              Connected
            </Text> : null
        }
        <TextInput
          value={this.state.messageToSend} 
          onChangeText={(value => this.setState({messageToSend: value}))} 
          placeholder="Type hereee..."
          style={styles.input} />
        <Button onPress={this.sendMessage.bind(this) } title="Send Message" />

      </View>
    );
  }


}

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

Replace the URL and other stuff with your own. For example, you have to put it like this:

const client = new Paho.MQTT.Client('something.something.ir', 1883, '123456');

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