Issues with TCP Socket Management and Ghost Data on ESP32 (Swift)

Hi everyone,

I'm developing an iOS app using Swift (Foundation, Network, and Combine) that communicates via TCP with a weighing scale. The scale uses an internal ESP32 module acting as a Wi-Fi Access Point (no internet access) specifically for data transmission. The app connects to this network and opens a socket to receive weight data and send command strings.

I’m currently facing two main issues:

Socket Management: The socket isn't closing properly. Occasionally, the app opens multiple simultaneous connections instead of maintaining a single one. Since the ESP32 has a client limit, these ghost connections eventually hang the communication module.

Invalid Outbound Data: The connection drops frequently because the scale receives invalid strings from the app. My logs show strange character sequences (like "gggggggggfdhj" or "vfgdddddddddddtty") being sent involuntarily. I haven't programmed these strings, and they cause the scale to terminate the session due to protocol violations.

How can I ensure proper socket closure and prevent these random data packets?

Additionally, a technical question: Is it possible to keep this TCP connection active in the background indefinitely on iOS while the user interacts with other apps?

Issues with TCP Socket Management and Ghost Data on ESP32 (Swift)
 
 
Q