Dumping data over ethernet with an arduino client

2019-04-14 12:15发布

问题:

I'm using an arduino ethernet to read data form sensors, and then would like to send data to a computer in another building to drive the logic/control in a piece of python software. I decided to sketch up a simple sketch in python/arduino that just sends text from the arduino to my python program over ethernet:

The arduino client code is mostly taken from the EthernetClient example:

#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);
  }
}

And then my python code:

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."

The response from the server is what i expect:

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.

But the client receives:

connecting...
connected.
This
disconnecting.

And seems to stop receiving the text from my server after the stream. Why is that?

Another question: Why is it that I asked my arduino to connect on port 1700, but python claims that it's receiving a request from port 1025?

thanks!