我正在使用 arduino 以太网从传感器读取数据,然后想将数据发送到另一栋建筑物中的计算机,以驱动 Python 软件中的逻辑/控制。我决定在 python/arduino 中绘制一个简单的草图,它只是通过以太网将文本从 arduino 发送到我的 python 程序:
arduino 客户端代码主要取自 EthernetClient 示例:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x40, 0x9F};
byte ip[] = {192, 168, 0, 172};
byte server[] = {192,168,0,17};
int port = 1700;
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
Ethernet.begin(mac, ip);
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port)) {
Serial.println("connected.");
//print text to the server
client.println("This is a request from the client.");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}
然后我的python代码:
import socket
host = ''
port = 1700
address = (host, port)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((address))
server_socket.listen(5)
print "Listening for client . . ."
conn, address = server_socket.accept()
print "Connected to client at ", address
//pick a large output buffer size because i don't necessarily know how big the incoming packet is
output = conn.recv(2048);
print "Message received from client:"
print output
conn.send("This is a response from the server.")
conn.close()
print "Test message sent and connection closed."
服务器的响应是我所期望的:
Listening for client . . .
Connected to client at ('192.168.0.172', 1025)
Message received from client:
This is a request from the client.
Test message sent and connection closed.
但客户收到:
connecting...
connected.
This
disconnecting.
并且似乎在流之后停止从我的服务器接收文本。这是为什么?
另一个问题:为什么我要求我的 arduino 连接到端口 1700,但 python 声称它正在接收来自端口 1025 的请求?
谢谢!