简体   繁体   English

使用pubsubclient连接到公共服务器

[英]Connect to a public server using pubsubclient

I am using PubSubClient library to subscribe to a server using a nodemcu. 我正在使用PubSubClient库使用nodemcu订阅服务器。 I tested the code using cloudMQTT and MQTTlens and it worked fine. 我使用cloudMQTT和MQTTlens测试了代码,并且运行良好。 In addition to that, I used MQTTlens to check mqtt connection with my pc. 除此之外,我还使用MQTTlens来检查与我的PC的mqtt连接。 In there, I did not specify username and password (I kept blank) and it worked just fine. 在这里,我没有指定用户名和密码(我保持空白),并且工作正常。 When I want to connect for a public server (ex: "tcp://11.111.111.111"), does not connect. 当我要连接公共服务器(例如:“ tcp://11.111.111.111”)时,无法连接。

code for nodemcu nodemcu的代码

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*****";
const char* password =  "****";
const char* mqttServer = "****";
const int mqttPort = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP8266Client")) {

      Serial.println("connected");  

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }

  client.publish("topic1", "Hello from ESP8266_tester1");
  client.subscribe("topic1");

}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  Serial.println();
  Serial.println("-----------------------");

}

void loop() {
  client.loop();
}

the result from the serial monitor 串行监视器的结果

结果

Any suggestion is welcome 欢迎任何建议

If you genuinely don't require a username and password then don't use the connect function that expects them: 如果您真的不需要用户名和密码,请不要使用需要它们的connect函数:

...
if (client.connect("ESP8266Client")) {
...

I see you are using a fairly generic client id - ESP8266Client . 我看到您使用的是相当通用的客户端ID- ESP8266Client Remember that all clients connecting to a broker must have a unique client id. 请记住,连接到代理的所有客户端必须具有唯一的客户端ID。 If you depoyed this sketch to two different devices they would not both be able to connect at the same time. 如果您将此草图部署到两个不同的设备,则它们将无法同时连接。

The problem was with the ip I have provided. 问题出在我提供的IP上。 IP does not require "tcp://" part. IP不需要“ tcp://”部分。 After removing that, the code worked well. 删除之后,代码运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM