无法通过 websockets 9001 将 ngx-mqtt 客户端连接到 public IP mosquitto mqtt 代理

Can't connect ngx-mqtt client to public IP mosquitto mqtt broker over websockets 9001

客户端

当我尝试将我的 angular 应用程序 运行ning ngx-mqtt 连接到具有面向 public 的 IP 地址的 mqtt 代理时,我最终在浏览器上收到这些错误(火狐)控制台日志:

这是使用 ngx-mqtt 在我的 angular 应用程序上设置连接详细信息的方式:

export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = 
{
   hostname: '<BROKER IP ADDRESS>',
   username: '<BROKER USERNAME>', 
   password: '<BROKER PASSWORD>', 
   port: 9001,
  //  protocol: 'ws',
  //  path: '/mqtt'

};

它们与我在 mqtt 代理电脑上创建的详细信息相匹配。

Broker/Server边

在我使用的 mqtt 代理上 mosquitto

我已经配置了 mosquitto.conf 文件,确保启用了 websockets 并且正确的端口 9001 作为额外的侦听器与端口 1883 的默认 mqtt 侦听器一起打开。

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

#include_dir /etc/mosquitto/conf.d

allow_anonymous false

password_file /etc/mosquitto/pwfile

listener 1883

listener 9001
protocol websockets

保存 mosquitto.conf 文件并重新启动 mosquitto 后,我 运行 mosquitto 命令和得到以下输出,它只说默认的 1883 端口是打开的:

根据 this blog 运行ning 命令 mosquitto -c /etc/mosquitto/mosquitto.conf 应该给我outout这告诉我端口 9001 已打开并正在侦听,并从 mosquitto.conf 文件加载。

但是当我运行那个命令时我没有得到任何输出。

我什至尝试确保为端口 9001 启用了防火墙和端口转发。

我也试过做一些建议的事情 in this question。但无论我尝试什么,我都无法让 websockets 在这个面向 IP mqtt 代理的 public 上工作。

奇怪的是,如果我尝试通过本地网络 mqtt 代理执行此操作,它工作正常,只有当我尝试连接到 public IP mqtt 代理时,我才会遇到这些问题。

如果它有助于工作的 LAN mqtt 代理是 raspberry pi 3 运行ning raspberry pi os 而 public IP WAN mqt 代理是运行宁 ubuntu 在英特尔核上。

如果有人能提供帮助,我们将不胜感激。

您没有得到预期输出的原因是因为 mosquitto 已经 运行作为一项服务。当你 运行 只是 mosquitto 它不会使用任何配置文件,所以它只会尝试在端口 1883 上启动一个监听器。

您必须在命令行上传递配置文件 mosquitto -c /etc/mosquitto/mosquitto.conf。但是,当服务仍在 运行ning 时,这仍然会失败。

你有2个选择。

  1. 先停止该服务,然后尝试在命令行上手动启动它以测试您的配置文件。您可以使用 sudo service mosquitto stop
  2. 只需重新启动服务 sudo service mosquitto restart,这将使它获取新的配置文件,然后也应该在端口 9001 上侦听。

好的,事实证明我的配置没有任何问题。由于某种原因,问题出在 Firefox 上,我用 Chromium 尝试了 运行 我的 angular 应用程序,它立即连接到 MQTT 代理。