Communication between two NodeMcu WIFI modules

The UDP code is part of much larger programs, so here are some extracts that may help. The code checks for received UDP packets on a defined port. If a received packet contains a defined string, the code takes some action.

First. I define configuration on the sender:

const uint16_t UDP_LOCAL_PORT =  8050;
const uint16_t UDP_REMOTE_PORT = 8051;
const char UDP_REMOTE_HOST[] =   "receiver";
char TRIGGER_STRING[] = "somestring";

I have the host name of the receiving nodeMCU ("receiver") configured on my home router. If you need to use an IP address, then you will need to change "receiver" to the IP address.

Configuration on the receiver:

const uint16_t UDP_LOCAL_PORT =  8051; // Must match UDP_REMOTE_PORT on sender
char TRIGGER_STRING[] = "somestring";  // Must match TRIGGER_STRING on sender

On both devices, I declare a global instance of the UDP class:

#include <WiFiUdp.h>
WiFiUDP UDP;

UDP is started by this code in setup() on both devices:

Serial.println("PROGRAM: starting UDP");
if (UDP.begin(UDP_LOCAL_PORT) == 1)
{
  Serial.println("PROGRAM: UDP started");
}
else
{
  Serial.println("PROGRAM: UDP not started");
}

On the sender, I use this code to send the trigger string to the receiver:

Serial.println("PROGRAM: sending trigger");
UDP.beginPacket(UDP_REMOTE_HOST, UDP_REMOTE_PORT);
UDP.write(TRIGGER_STRING);
UDP.endPacket();

On the receiver, this code checks received UDP packets to see if they contain the trigger string:

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet,
int packetSize = UDP.parsePacket();
if (packetSize > 0)
{
  Serial.print("PROGRAM: received UDP packet of size ");
  Serial.println(packetSize);
  Serial.print("PROGRAM: from ");
  IPAddress remote = UDP.remoteIP();
  for (int i = 0; i < 4; i++)
  {
    Serial.print(remote[i], DEC);
    if (i < 3)
    {
      Serial.print(".");
    }
  }
  Serial.print(", port ");
  Serial.println(UDP.remotePort());
  UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
  Serial.print("PROGRAM: contents: ");
  Serial.println(packetBuffer);
  if (strncmp(packetBuffer, TRIGGER_STRING, strlen(TRIGGER_STRING)) == 0)
  {
    Serial.println("PROGRAM: trigger received");
    // DO YOUR STUFF HERE
  }
  delay(10);
}