Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file:


  const mqtt = require('mqtt')
  const client  = mqtt.connect('mqtt://localhost:1883')
  topic = 'testTopic'

  client.on('connect', ()=> {
    client.subscribe(topic)
  })

  client.on('message', function (topic, message) {
    console.log(message.toString())
  })

I successfully connected to both hivemq-cli and the hivemq server. I then created a new topic named testTopic under the Test1 subscriptions and allowed another user to subscribe to it. https://i.sstatic.net/lv3Rk.png

Using hivemq-cli, everything seemed fine as shown in my terminal:

testTopic3@localhost> sub -t testTopic -s
Hello
Hello
Hello
Hello
Hello
Hello
Hi
Hi
Hi

However, upon running npm start, my web application reported an error stating: "Firefox can't establish a connection to the server at ws://localhost:1883/", and returned nothing.

I have been struggling with this issue for a day now, so any assistance would be greatly appreciated. Thank you!

Answer №1

Your web application utilizes websockets (ws://), likely on a separate port from the MQTT port 1883 (mqtt://).

Answer №2

To set up the listener in the HiveMQ configuration (conf/config.xml), ensure you specify the correct port and path when connecting your client. The default setup does not include a WebSocket listener.

Here is an example of how to configure it:

<hivemq>
    <listeners>

        <!-- Default TCP Configuration -->
        <tcp-listener>
            <port>1883</port>
            <bind-address>0.0.0.0</bind-address>
        </tcp-listener>

        <!-- WebSocket Configuration -->
        <websocket-listener>
            <port>8000</port>
            <bind-address>0.0.0.0</bind-address>
            <path>/mqtt</path>
            <subprotocols>
                <subprotocol>mqttv3.1</subprotocol>
                <subprotocol>mqtt</subprotocol>
            </subprotocols>
            <allow-extensions>true</allow-extensions>
        </websocket-listener>
    </listeners>
<hivemq>

Once configured, connect your client to ws://localhost:8000/mqtt

For further details on configuration settings, refer to the documentation:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The Object #<Object> does not contain a function named 'Schema'

Below is the user model schema that we are using. However, when I try to run it on my localhost, I encounter an error: TypeError: Object # has no method 'Schema' // app/models/user.js // Required modules var neo4j = require('neo4j'); ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

The expected React component's generic type was 0 arguments, however, it received 1 argument

type TCommonField = { label?: string, dataKey?: string, required?: boolean, loading?: boolean, placeholder?: string, getListOptionsPromissoryCallback?: unknown, listingPromissoryOptions?: unknown, renderOption?: unknown, getOptionLabelFor ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

Deactivate certain choices in React Select

Encountering difficulties disabling specific options in a large list within a React Select component. A total of 6,500 options are loaded into the select element. Initially, there were issues with search functionality lagging, but this was resolved by impl ...

Searching for $or command in express.js

Is it possible to use $or in the app.get() function of an express.js application? For example, how would I write a find() query that includes $or like this: db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) I'm curious about ...

Create a custom npm package that is compatible with frontend environments like create-react-app. Ensure you have a suitable loader in place to handle the specific file type of the module

After developing a node module and releasing it as a node package, I encountered an issue when trying to use it in frontend applications (specifically with a 'create-react-app'). The error message that appeared stated: Module parse failed: Unexp ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...

Unpredictable hues in a headline

Can the text in an H1 tag have each word appear in a different random color, and then refresh to show new random colors? I have 5 specific colors in mind that I'd like to use. How would I go about coding this? ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

Post the information from a webpage onto your Instagram story

I'm currently developing a web application that generates text content, with future plans to include images as well. I want to integrate a share button that allows users to easily add this generated content to their Instagram story. The intended flow ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...

What is the best way to extract all image URLs from a website using JavaScript?

There are various methods to retrieve image src urls using JavaScript, such as utilizing document.images or by targeting all img elements and fetching their src attributes. However, I am currently unable to extract the image urls specified within CSS styl ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

Error encountered during npm installation caused by the extract-text-webpack-plugin

I encountered an error while attempting to install the extract-text-webpack-pluginpm plugin. extract-text-webpack-plugin <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f12124c5e495a125b5a495e4f4f7f0f110e110f">[email  ...

What is the best way to activate a Rails controller action in response to a JavaScript event?

I'm in the process of developing a Rails application and I have a requirement to trigger an Update action from one of my controllers based on a JavaScript event. Here's what my controller action looks like currently: def update @subscrip ...

Combining Multiple Tables Using Knex SQL Joins and Storing the Result in an Array

At the moment, I'm utilizing Knex to carry out queries on a MSSQL database. In my schema, there is a table named "Meals" which has the following columns: Id Additionally, there is also a table named "Vegetables" with the following columns: Id Meal ...