我一直在尝试通过 MQTT 从我的 Arduino 向我的亚马逊网络服务器发送消息。以下代码连接以太网客户端,但不连接 MQTT 客户端。为什么我的 MQTT 客户端无法连接?
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
byte mac[] = { 0x12, 0x42, 0x98, 0x85, 0x49, 0x3A }; //MAC address of server
char server[] = "http://52.1.29.117/"; //web address of server
IPAddress ip(172, 31, 51, 13); //IP address of server
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
EthernetClient ethClient;
PubSubClient client(server, 80, callback, ethClient);
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
if (ethClient.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
ethClient.println("GET /search?q=arduino HTTP/1.1");
ethClient.println("Host: www.google.com");
ethClient.println("Connection: close");
ethClient.println();
}
else {
Serial.println("connection failed");
}
// if (client.connect(server)) {
if (client.connect(server, "ubuntu", "")) {
Serial.print("Data sent/n");
client.publish("hello/world","hello world");
client.subscribe("hiWorld");
}
else {
Serial.print("nope");
}
}
void loop()
{
client.loop();
}