You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular应用无法连接Mosquitto测试站点test.mosquitto.org问题求助

Angular对接test.mosquitto.org测试站连接失败解决方案

问题描述

使用Angular开发对接MQTT Mosquitto测试站点,操作后出现如下报错:
WebSocket connection to 'wss://test.mosquitto.org:8080/' failed:

原有配置

环境配置文件mqtt属性:

mqtt: {
    server: 'test.mosquitto.org',
    protocol: "wss",
    port: 8080,
  }

MQTT服务代码:

export class EventMqttService {

  private endpoint: string;

  constructor(
    private _mqttService: MqttService,
  ) {
    this.endpoint = ''
  }

  topic(topic ? : string): Observable < IMqttMessage > {
    let topicName = `${this.endpoint}${topic}`;
    return this._mqttService.observe(topicName);
  }
}

组件调用代码:

notificationSubscribe() {
    console.log('STARTING dataMqtt...');
    this.notificationSubscription = this.eventMqtt.topic()
      .subscribe(
        (dataMqtt: IMqttMessage) => {
          console.log('dataMqtt: ', dataMqtt);
        }
      )
  }

已尝试的无效操作

  • 将协议改为ws、端口保留8080,报错不变
  • 在mqtt配置中添加path:'/mqtt'参数,报错变为WebSocket connection to 'ws://test.mosquitto.org:8080/mqtt' failed:

修复方案

按照以下步骤调整即可解决问题:

  • 端口与协议匹配修正
    test.mosquitto.org公开WebSocket服务的端口对应规则为:未加密ws协议用8080端口,加密wss协议用8081端口。localhost开发环境直接使用未加密协议即可,避免混合内容错误,配置调整为:
mqtt: {
    server: 'test.mosquitto.org',
    protocol: "ws",
    port: 8080,
    path: "/",
    clientId: `mqtt_${Math.random().toString(16).slice(3)}`
  }
  • 补充必填订阅主题
    MQTT协议不允许订阅空主题,你当前调用topic()方法时没有传入具体主题参数,属于不符合规范的操作。可以使用公开测试主题进行调试,调用代码调整为:
notificationSubscribe() {
    console.log('STARTING dataMqtt...');
    // 传入合法的订阅主题
    this.notificationSubscription = this.eventMqtt.topic('test/#')
      .subscribe(
        (dataMqtt: IMqttMessage) => {
          // 转码payload后再打印更易读
          console.log('dataMqtt: ', dataMqtt.payload.toString());
        }
      )
  }
  • 额外排查项
    如果调整后仍然连接失败,先关闭本地代理、VPN工具,避免端口请求被拦截;同时检查MQTT依赖的初始化配置,不需要填写用户名、密码,test.mosquitto.org公开服务无需鉴权。

内容的提问来源于stack exchange,提问作者Federico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:09:01