tcp - 通过以太网、IP 进行简单的 Arduino 客户端服务器通信
问题描述
两个 Arduino 板之间的简单以太网通信。我使用了两个 Arduino UNO 板,两个 Arduino 以太网扩展板。
这是我的服务器代码
//Server
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet are optional.
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//the IP address for the shield:
byte ip[] = { 192,168,1,180 };
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };
EthernetServer server = EthernetServer(10001);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}
}
这是我的客户代码
//Client
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xEC};
IPAddress ip(192,168,1,177);
IPAddress server(192,168,1,180);
EthernetClient client(10001);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 10001)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
我将这两个代码输入到两个 Arduino 板上。接线及其他连接正确可靠。但我从客户端串行监视器得到了这个输出
connecting...
connection failed
disconnecting.
根据我的观点,客户端代码中可能会发生错误。你能帮我找出错误吗?
解决方案
推荐阅读
- implementation - 如何实现闪电网络的 RSMC 部分?
- python - 如何找出 RFECV 选择的特征名称?
- python - 如何同时从单词列表中检查和删除“/”和“-”
- sqlite - sqlite 从列中删除平方米符号
- javascript - 在客户端使用PHP或JavaScript从大量数据中通过大量关键字一一搜索
- jquery - 在通过 ajax 保存之前检查字符长度
- .net-core - 强制更新传递 nuget 包依赖项的最佳方法?
- schedule - 到达率的 AnyLogic 时间表
- vue.js - 如何在安装生命周期方法之前使用 vue.js?
- swift - UIApplication.shared.open 在 ios 13 中不起作用