Sending and Receiving unsigned long using WiFiClient (TCP).

Hello , In my project I am using 2 ESP8266 for communicate with each other.

The client has to send sensor data to server, Unfortunately I don't know how to receive/print data correctly on the server side to serial monitor , The data received/prints as gibberish.

Client side :

void SendTCP(unsigned long pulseLength)
{
 
  if (!client.connect(ipBroadCast, tcpRemotePort)) {
    Serial.println("TCP Connection failed");
    Serial.println(client.connect(ipBroadCast, tcpRemotePort));
    return;
  }else
  {
    Serial.println("TCP Connected");
  }
  
 client.write((uint8_t*) &pulseLength,4);

}

Server side :

void ReceiveTCP()
{
   WiFiClient client = server.available();
   if (client) {

    if (client.connected()) {
      Serial.println("Client Connected ");
    }


    // Wait for data from client to become available
     while (client.connected() && !client.available()) {
        delay(1);
     }
  
     // Read incoming message
     if (client.available() > 0) {
      Serial.print("incoming :");
      int size;
      while ((size = client.available()) > 0) {
        uint8_t* msg = (uint8_t*)malloc(size);
        size = client.read(msg, size);
        Serial.write(msg, size);
        free(msg);
      }
    
    }
  
    // close the connection:
    client.stop();
  }
}

*Note : with same sending method I am able to read the data correctly on PC using server
written in java :

long pulseLength = 0;

byte[] recivedULBuffer = new byte[4];

inputStreamFromClient.read(recivedULBuffer);

for (int i = 0; i < recivedULBuffer.length; i++){

pulseLength += ((long) recivedULBuffer[i] & 0xffL) << (8 * i);

}

Thanks !

 client.write((uint8_t*) &pulseLength,4);

The size should NOT be hardcoded. Use sizeof() instead.

        uint8_t* msg = (uint8_t*)malloc(size);
        size = client.read(msg, size);
        Serial.write(msg, size);
        free(msg);

You know how much data you sent. Why do you need to use dynamic memory allocation to create a 4 byte array?

Writing the bytes is NOT the same as writing the unsigned long.

Where are you sending the Serial data? The Serial Monitor does NOT expect binary data.

You need to convert the bytes back to an unsigned long, and print() that.

Googling for How to convert uint8_t* to unsigned long,
Meanwhile if you know how I would like to know (: Thanks !

Thanks you very much , you were right (:
Friend from ESP forums helped me here is the correct conversion if some one will need it in the future :

while ((size = client.available()) > 0) {
unsigned long * msg = (unsigned long *)malloc(size);
size = client.read((uint8_t *)msg, size);
String str = String("Value = ") + (*msg);
Serial.println(str);
free(msg);
}