The EtherntServer currently requires at least one byte to be sent from a client before the connection is noticed as open (Ethernet needs to receive one byte to see new connection - Networking, Protocols, and Devices - Arduino Forum). This behaviour is extremely difficult to change outside the library itself. The following change allows all existing code to function but introduces the ability to set the waitForInput flag to false and hence no longer require the initial byte.
--- EthernetServer.cpp.orig 2014-02-13 11:54:08.000000000 +1100
+++ EthernetServer.cpp 2014-02-13 13:10:55.000000000 +1100
@@ -48,7 +48,7 @@
}
}
-EthernetClient EthernetServer::available()
+EthernetClient EthernetServer::available(bool waitForInput)
{
accept();
@@ -57,7 +57,7 @@
if (EthernetClass::_server_port[sock] == _port &&
(client.status() == SnSR::ESTABLISHED ||
client.status() == SnSR::CLOSE_WAIT)) {
- if (client.available()) {
+ if (client.available() || !waitForInput) {
// XXX: don't always pick the lowest numbered socket.
return client;
}
@@ -89,3 +89,4 @@
return n;
}
+
--- EthernetServer.h.orig 2014-02-13 11:54:16.000000000 +1100
+++ EthernetServer.h 2014-02-13 13:09:59.000000000 +1100
@@ -12,7 +12,8 @@
void accept();
public:
EthernetServer(uint16_t);
- EthernetClient available();
+ EthernetClient available() { return available(true); }
+ EthernetClient available(bool waitForInput);
virtual void begin();
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
The exact behaviour given in Ethernet - Arduino Reference is supported. However, with the modified library you can also support code like:
void loop() {
EthernetClient client = server.available(false);
if (client) {
delay(50); // Wait 50ms between pings (about 20 pings/sec).
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
client.print("Ping: ");
client.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result
client.println("cm");
client.stop();
}
}
Which is easily polled from scripting languages with no extra requirement for sending a byte.
EthernetServer.cpp.patch (666 Bytes)
EthernetServer.h.patch (447 Bytes)