如何在我的react-native应用程序中将自己的代理与tcp:// uri一起使用?

时间:2019-07-24 15:32:39

标签: react-native mqtt

这听起来可能是重复的,但事实并非如此。 我是React-Native的新手。 我正在尝试使用“ react-native-paho-mqtt”库编写一个MQTT-Client应用程序,该库应该能够使用此uri连接到我自己的代理:tcp://217.218.171.92:1883 但显然uri必须仅以“ wss”开头!!! 如何使我的应用使用tcp://? 除此之外,有可能吗?

这是我的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({
  ...
});

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

react-native-paho-mqtt仅支持 WebSocket

因为react-native-paho-mqtt不支持开箱即用的原始TCP

如果您使用real-native-tcp配置客户端,则可能会在代码上出现。

一个模块的例子告诉我们这是不可能的。

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

答案 1 :(得分:0)

对于新的Google员工:您可以使用react_native_mqt。 例如,在您设法正确安装该库之后,就可以是您的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,
  },
});

用您自己的URL和其他内容替换。例如,您必须这样输入:

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