这是一个有关运行以太网的arduino设备的问题,该设备可以在Linux机器上使用python在我的网络上进行访问。
arduino代码在这里:
#include <Ethernet.h>
#include <SPI.h>
#define ETH_RST 9 // ethernet reset pin
#define ETH_CS 10 // ethernet chip select
String inputString = "";
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 0, 1, 18);
EthernetServer server(5000);
void setup() {
pinMode(ETH_CS, INPUT_PULLUP);
pinMode(ETH_RST, INPUT_PULLUP);
pinMode(ETH_RST, OUTPUT); // should be high
digitalWrite(ETH_RST, HIGH); // reset is active low
digitalWrite(ETH_RST, LOW);
delay(1);
digitalWrite(ETH_RST, HIGH);
Ethernet.init(ETH_CS);
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000); // give it some time
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n') {
Serial.print("cmd: ");
Serial.println(inputString);
client.print("return: ");
client.println(inputString);
client.flush();
inputString = "";
}
else {
inputString += c;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
Serial.println("client disconnected");
client.stop();
}
}
我正在使用此python代码通过名为client.py的程序访问服务器:
#!/usr/bin/env python2.7
import socket
HOST = '10.0.1.18'
PORT = 4999
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
while 1:
message = raw_input(" -> ")
if (message == 'quit'):
break
print ('message ' + message)
client_socket.send(message + '\n')
data = client_socket.recv(1024).decode() # get response
print('Received from server: ' + data) # show reponse
client_socket.close() # close the connection
所以让我们运行client.py-这个会话中显示了奇怪的东西。
$ ./client.py
-> m1
message m1
Received from server: return:
-> m2
message m2
Received from server: m1
-> m3
message m3
Received from server: return: m2
-> m4
message m4
Received from server: return: m3
-> m5
message m5
Received from server: return: m4
-> quit
所以我期望如果我发送m1,我会得到m1的。但是当我使用
发送消息时
client_socket.send(text)
然后执行
data = client_socket.recv(1024).decode()
返回的数据来自先前的send()。我不明白。有建议吗?