@@ -5,9 +5,40 @@ import { StyleSheet, Text, View } from 'react-native';
55import MqttClient , { ClientEvent } from '@ko-developerhong/react-native-mqtt' ;
66
77export default function App ( ) {
8+ const [ mode ] = useState < 'mqtt' | 'mqtts' > ( 'mqtts' ) ;
89 const [ result , setResult ] = useState < any > ( ) ;
910
1011 useEffect ( ( ) => {
12+ if ( mode !== 'mqtts' ) return ;
13+ ( async ( ) => {
14+ try {
15+ await MqttClient . connect ( 'mqtts://test.mosquitto.org:8883' , {
16+ autoReconnect : false ,
17+ password : 'password' ,
18+ username : 'tablet' ,
19+ } ) ;
20+ MqttClient . on ( ClientEvent . Connect , ( reconnect ) => {
21+ console . log ( 'reconnect : ' , reconnect ) ;
22+ } ) ;
23+ MqttClient . on ( ClientEvent . Error , ( error ) => {
24+ console . log ( 'error : ' , error ) ;
25+ } ) ;
26+ MqttClient . on ( ClientEvent . Disconnect , ( cause ) => {
27+ console . log ( 'Disconnect cause : ' , cause ) ;
28+ } ) ;
29+ MqttClient . on ( ClientEvent . Message , ( topic , message ) => {
30+ console . log ( 'topic : ' , topic ) ;
31+ console . log ( 'message : ' , message . toString ( ) ) ;
32+ setResult ( message . toString ( ) ) ;
33+ } ) ;
34+ } catch ( err ) {
35+ console . error ( 'catch error: ' , err ) ;
36+ }
37+ } ) ( ) ;
38+ } , [ mode ] ) ;
39+
40+ useEffect ( ( ) => {
41+ if ( mode !== 'mqtt' ) return ;
1142 ( async ( ) => {
1243 try {
1344 await MqttClient . connect ( 'mqtt://test.mosquitto.org' , { } ) ;
@@ -31,7 +62,7 @@ export default function App() {
3162 console . error ( 'catch error: ' , err ) ;
3263 }
3364 } ) ( ) ;
34- } , [ ] ) ;
65+ } , [ mode ] ) ;
3566
3667 return (
3768 < View style = { styles . container } >
0 commit comments