EthernetClient - What if I don't read what's available?

I recently picked up an Arduino Mega 2560 and an Ethernet Shield 2, and have been experimenting with their capabilities. I want to make sure I understand what I'm working with before I get too deep into a larger project.

I currently have a button between Pin 11 and Ground. Pressing the button sends a signal to a simple PHP test that I'm hosting on a spare server. My test code looks something like this

#include <SPI.h>
#include <Ethernet.h>

const byte macMain[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x85, 0xEE };
const byte ipMain[] = { 192, 168, 1, 103 };

const byte ipGateway[] = { 192, 168, 1, 1 };
const byte ipDNS[] = { 75, 153, 176, 9 };
const byte ipSubnet[] = { 255, 255, 255, 0 };

const int pinButton = 11;
const char server[] = "(example).addftoxic.com";

EthernetClient client;

void setup() {
  Serial.begin(9600);
  pinMode(pinButton, INPUT_PULLUP);
  Ethernet.begin(macMain, ipMain, ipDNS, ipGateway);
}

void loop() {
  //Check for pressed button
  if(digitalRead(pinButton) == LOW){
    if(!client.connected()){
      client.connect(server, 80);
    }
    
    client.println("POST /mute.php HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println();

    //Lazy debounce
    delay(500);
  }

  //Receive response
  if(client.available()){
    char c = client.read();
    Serial.print(c);

    //Extra space at the bottom after reading everything
    if(!client.available()){
      Serial.println();
      Serial.println();
    }
  }
}

This works well. When I press the button, the PHP script is run (it simply creates a file), and the Serial Monitor displays the response

HTTP/1.1 200 OK
Date: Fri, 26 Nov 2021 05:23:02 GMT
Server: Apache
Content-Length: 29
Content-Type: application/json

{"changed":true,"muted":true}

Currently, the code doesn't really do anything other that display the result in the Monitor, and in a practical scenario I'd probably want to parse the JSON.
What I'm curious about is: what if I don't need any information from the response? If I were to comment out the entire "Receive response" block of code, the request is still sent (as evidenced by my test server). Would all the ignored responses end up filling the client's buffer after a while, and cause it to malfunction?
If I were to not need any information from the response (I can imagine being in this type of scenario), should I call client.read() anyway, just to clear the buffer?

if you close the connection, then you don't have to read all the available data.

Thanks, Juraj, that makes a lot of sense. A simple

if(client.available()){
    client.stop();
  }

at the end of the loop() is a quicker than reading a few more times, and does clear the buffer according to my experiments.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.