{ useE" /> { useE" /> { useE"/>

How to Connect to Mosquitto MQTT server in VM using Typescript

86 Views Asked by At
import React, { useEffect } from "react";
import mqtt, { MqttClient } from "mqtt";
import { v4 as uuidv4 } from "uuid";

const Subscribe = () => {
  useEffect(() => {
    // MQTT Topic to subscribe to
    const topic: string = "jobstatus";
    const mqttBrokerUrl = 'wss://myipaddress:8080/mqtt'; 
    // Connect options for MQTT client
    const options = {
        clientId: 'Testing',
        username: 'admin', 
        password: 'admin',
    };
    const client: MqttClient = mqtt.connect(mqttBrokerUrl, options);
    function handleMessage(topic: string, message: Buffer) {
      const messageString: string = message.toString();
      console.log(`Received message on topic "${topic}": ${messageString}`);
      updateUI(messageString);
    }

    client.on("connect", () => {
      console.log("Connected to MQTT broker");
      client.subscribe(topic, (err) => {
        if (err) {
          console.error(`Error subscribing to topic "${topic}": ${err}`);
        } else {
          console.log(`Subscribed to topic "${topic}"`);
        }
      });
    });

    //To Handle incoming MQTT messages
    client.on("message", handleMessage);

    function updateUI(message: string) {
      console.log("Updating UI with message:", message);
    }

    // Cleanup function
    return () => {
      client.unsubscribe(topic, (err) => {
        if (err) {
          console.error(`Error unsubscribing from topic "${topic}": ${err}`);
        } else {
          console.log(`Unsubscribed from topic "${topic}"`);
        }
        client.end(); // Close MQTT connection
      });
    };
  }, []); 
  return (
    <div>
      <div>MQTT Messages...</div>
    </div>
  );
}; 

This is the component which I created to subscribe to a topic in MQTT and to show the message in front end. While running this I get WebSocket connection to 'wss://20.198.14.124/mqtt error when inspected.

I have tried altering my mosquitto.conf file as below.

listener 1883
listener 8080
protocol websockets
allow_anonymous true

while changing the Mosquitto config and running, I get the error as:

1702358221: mosquitto version 1.6.9 starting
1702358221: Config loaded from /etc/mosquitto/mosquitto.conf.
1702358221: Opening ipv4 listen socket on port 1883.
1702358221: Error: Cannot assign requested address
1702358231: mosquitto version 1.6.9 starting
1702358231: Config loaded from /etc/mosquitto/mosquitto.conf.
1702358231: Opening ipv4 listen socket on port 8080.
1702358231: Error: Cannot assign requested address.

My Mosquitto server runs on an azure vm with ip-> 20.193.14.124.

I need to subscribe to topic and display those messages in frontend. Could you all help me with this problem?

0

There are 0 best solutions below