Cannot communication Wifi UDP from IoT device with Unity Editor

Hello all :smile:
I am struggling to find reasons for this and asking for help for a problem.

I am using an Arduino Nano IoT 33 Board with ESP32(NINA-W102) Wifi chip for this communication.

The problem is I can smoothly communicate this device for both read/write WIFI UDP communication both in my different c++ console program and a serial port monitor program (You can find it here: https://blog.daum.net/pg365/276).

Even I can communicate with the c++ console program and Unity via LAN UDP communication.

So the code for all Arduino code, c++ console program code, and even the c# code in Unity have NO PROBLEM…

I also gave permission to ports I am using on Windows Firewall.

The Error message I got here is "System.Net.Sockets.SocketException (0x80004005): " Failing to connect the device…

Similar issues in forums said just restarting solved the problem,
but in my case, the communication was never successful and restart didn’t help.
I will really appreciate any comments from you.

Thanks so much in advance.

I am attaching my c# code and Arduino code for you just for references
Arduino code:

#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>

#include <WiFiNINA.h>

#include <Arduino_LSM6DS3.h>
#include <SPI.h>
#include <WiFiUDP.h>

//#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "----";        // your network SSID (name)
char pass[] = "----";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192, 168, 1, 31);   // name address for Google (using DNS)

WiFiUDP Udp;
unsigned int localUdpPort = 58432;

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
int sensorValue = 0;
float aX, aY, aZ;
float gX, gY, gZ;
char tmpAx[7]; char tmpAy[7]; char tmpAz[7];
char tmpGx[7]; char tmpGy[7]; char tmpGz[7];
//String tmpAx; String tmpAy; String tmpAz;
//String tmpGx; String tmpGy; String tmpGz;
char cBuf[128];
const char * spacer = ", ";

unsigned long lastConnectionTime = 0;            // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 20L; // delay between updates, in milliseconds
void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
 
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (true); // halt program
  }
  Serial.println("IMU initialized!");
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(3000);
  }
  Serial.println("Connected to wifi");

  if (Udp.begin(localUdpPort)){
    Serial.println("UDP connected");
  }
 
  printWifiStatus();
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  int packetSize = Udp.parsePacket();
  if (packetSize) { //packetSize
    Serial.println("Recieved packet UDP");
    //client.println("Connection from Arduino");
    //client.write("Connection from Arduino 2\n", 30);
    sensorValue = analogRead(analogInPin);
    // Read IMU
    if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {
      IMU.readAcceleration(aX, aY, aZ);
      IMU.readGyroscope(gX, gY, gZ);
    }
    dtostrf(aX, 7, 3, tmpAx);
    dtostrf(aY, 7, 3, tmpAy);      dtostrf(aZ, 7, 3, tmpAz);
    dtostrf(gX, 7, 3, tmpGx);      dtostrf(gY, 7, 3, tmpGy);      dtostrf(gZ, 7, 3, tmpGz);
    //tmpAx = String(aX); tmpAy = String(aY); tmpAz = String(aZ);
    //tmpGx = String(gX); tmpGy = String(gY); tmpGz = String(gZ);
    sprintf(cBuf, "Arduino Out: %d, %s, ", sensorValue, tmpAx, tmpAz); //??????  I don't know....
                                       //sprintf(cBuf,"%s, %s, %s\n", cBuf, tmpAy, tmpAz);
    Serial.print("Connected to server : ");
    Serial.print(cBuf);

    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Serial.println(Udp.remoteIP());    Serial.println(Udp.remotePort());
    Udp.write(cBuf);
    Udp.endPacket();
    delay(100);
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

char *dtostrf(double val, signed char width, unsigned char prec, char *sout) {
  char fmt[20];
  sprintf(fmt, "%%%d.%df", width, prec);
  sprintf(sout, fmt, val);
  return sout;
}

Unity c# code:

using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;


public class UDPReciever : MonoBehaviour
{
    Thread udpListeningThread;
    public int portNumberReceive;
    UdpClient receivingUdpClient;
    string[] delimiters = { ", ", "," };
    string[] data;

    void Start()
    {
        initListenerThread();
     
    }

    void initListenerThread()
    {
        Debug.Log("Started on : " + portNumberReceive.ToString());
        udpListeningThread = new Thread(new ThreadStart(UdpListener));

        // Run in background
        udpListeningThread.IsBackground = true;
        udpListeningThread.Start();
        Debug.Log("Start");
    }

    public void UdpListener()
    {
        if (receivingUdpClient == null)
        {
            receivingUdpClient = new UdpClient(portNumberReceive);
        }
        while (true)
        {
            //Listening
            try
            {             
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.27"),58432);
                receivingUdpClient.Client.ReceiveTimeout = 150;
                Debug.Log(RemoteIpEndPoint);
                // Blocks until a message returns on this socket from a remote host.
                byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
             
                Debug.Log("Recieve");
                if (receiveBytes != null)
                {
                    string returnData = Encoding.UTF8.GetString(receiveBytes);
                    Debug.Log("Message Received" + returnData.ToString());
                    Debug.Log("Address IP Sender" + RemoteIpEndPoint.Address.ToString());
                    Debug.Log("Port Number Sender" + RemoteIpEndPoint.Port.ToString());

                    data = returnData.Split(delimiters, StringSplitOptions.None);
                    Debug.Log(data);
                }
            }
            catch (Exception e)
            {
                Debug.Log("Error");
                Debug.Log(e.ToString());
            }
        }
        Debug.Log("Loop");
    }

    void OnDisable()
    {
        Debug.Log("UDPDisable");
        if (udpListeningThread != null && udpListeningThread.IsAlive)
        {
            udpListeningThread.Abort();
        }

        receivingUdpClient.Close();
    }
}

Found that the code is working on Unity 2017 but not on Unity 2019 and 2020 what I am currently working on.
Any comments for me to make it work in 2020ver?

I’ve got I had to use HLAPI over Unity 5.